uacs2024

导航

leetcode814. 二叉树剪枝。如果想到使用递归还是很简单的

814. 二叉树剪枝

有一点疑问,为什么不能先         if(!root->left&&!root->right&&root->val==0) return nullptr;     ?

class Solution {
public:
    TreeNode* pruneTree(TreeNode* root) {
        if(root==nullptr) return nullptr;
        root->left=pruneTree(root->left);
        root->right=pruneTree(root->right);
        if(!root->left&&!root->right&&root->val==0) return nullptr;
        return root;
    }
};

 

posted on 2022-11-22 15:13  ᶜʸᵃⁿ  阅读(9)  评论(0编辑  收藏  举报