【LeetCode】814. Binary Tree Pruning

一道树的剪枝,起初的想法是设一个函数,判断当前节点的子树是否含1,后来发现,后序遍历删除值为0的叶子节点就可以了。

代码如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    
    TreeNode* pruneTree(TreeNode* root) {
        if(root==NULL)return NULL;
        root->left = pruneTree(root->left);
        root->right = pruneTree(root->right);
        if(root->left==NULL&&root->right==NULL&&root->val==0)
        {
            return NULL;
        }    
        return root;
    }
};

 

相关文章:

  • 2021-11-06
  • 2021-12-22
  • 2021-08-25
  • 2022-02-02
  • 2022-02-04
  • 2021-10-11
  • 2021-12-30
  • 2021-07-27
猜你喜欢
  • 2022-01-08
  • 2022-01-30
  • 2021-05-23
  • 2022-12-23
  • 2022-01-10
  • 2021-12-24
  • 2022-02-24
相关资源
相似解决方案