Binary Tree Pruning(C++二叉树剪枝)

解题思路:

(1)后序遍历

(2)和Delete Leaves With a Given Value题目类似

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

 

你可能感兴趣的:(C++,LeetCode,二叉树,leetcode,c++)