[树] leetcode 814 Binary Tree Pruning

problem:https://leetcode.com/problems/binary-tree-pruning/

        一道非常简单的tree题目,根据题意模拟剔除不包含0的子树即可。

class Solution {
public:
    bool dfs(TreeNode* p)
    {
        if (!p) return false;
        bool bLeft = dfs(p->left);
        bool bRight = dfs(p->right);
        
        if (!bLeft)
        {
            p->left = nullptr;
        }
        if (!bRight)
        {
            p->right = nullptr;
        }
        if (bLeft || bRight || p->val == 1)
        {
            return true;
        }

        return false;    

    }
    TreeNode* pruneTree(TreeNode* root) {
        dfs(root);
        return root;
    }
};

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11287819.html