欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 814. 二叉树剪枝(DFS统计和)

程序员文章站 2022-05-20 20:25:24
...

二叉树剪枝
check()函数统计某一棵子树的节点值的和,然后,如果左子树为0,将root->left置为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) {
        int sum = check(root);
        if(!sum){
            root = nullptr;
        }
        return root;
    }
    bool check(TreeNode* root){
        if(!root){
            return 0;
        }
        int leftSum = check(root->left) ;
        int rightSum = check(root->right);
        if(!leftSum){
            root->left = nullptr;
        }
        if(!rightSum){
            root->right = nullptr;
        }
        return root->val + leftSum + rightSum;
    }
};