美文网首页
814.binary-tree-pruning(do again

814.binary-tree-pruning(do again

作者: Optimization | 来源:发表于2020-05-26 11:51 被阅读0次
    问题:

    1.为什么能从尾到头进行删除呢?因为是后续遍历。
    2.不能delete root节点,否则会由于问题。

    正文:
    class Solution {
    public:
        TreeNode* pruneTree(TreeNode* root) {
            if(!root) return nullptr;
            root->left = pruneTree(root->left);
            root->right = pruneTree(root->right);
            if(root->val == 0 && root->left == nullptr 
                && root->right == nullptr){
                // 不能把根节点给删除了
                // delete root;
                return nullptr;
            } else{
                return root;
            }
        }
    };
    

    相关文章

      网友评论

          本文标题:814.binary-tree-pruning(do again

          本文链接:https://www.haomeiwen.com/subject/sxmmahtx.html