Skip to content

Latest commit

 

History

History
64 lines (53 loc) · 1.8 KB

814.binary_tree_pruning.md

File metadata and controls

64 lines (53 loc) · 1.8 KB

814.Binary Tree Pruning

难度:Medium

给定二叉树根结点 root ,此外树的每个结点的值要么是 0,要么是 1。

返回移除了所有不包含 1 的子树的原二叉树。

( 节点 X 的子树为 X 本身,以及所有 X 的后代。)

示例1: 输入: [1,null,0,0,1] 输出: [1,null,0,null,1] 1028_2.png

解释: 只有红色节点满足条件“所有不包含 1 的子树”。 右图为返回的答案。

示例2: 输入: [1,0,1,0,0,0,1] 输出: [1,null,1,null,1] 1028_1.png

示例3: 输入: [1,1,0,1,1,0,1,0] 输出: [1,1,0,1,1,null,1] 1028.png

说明: 给定的二叉树最多有 100 个节点。 每个节点的值只会为 0 或 1 。

递归剪枝,如果左子树或者右子树都为空,而且此时节点值为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 {
bool isRoot = true;
public:
    TreeNode* pruneTree(TreeNode* root) {
        if(!root) return root;
        if(!root->left && !root->right) return  (!isRoot && root->val == 0) ? nullptr: root;
        isRoot=false;
      // cout<<root->val<<endl;
        if(root->left   ) root->left = pruneTree(root->left);
        if(root->right) root->right = pruneTree(root->right);
        if( root->val ==0 && !root->left && !root->right) return nullptr;
        return root; 
    }
};

执行用时 :8 ms, 在所有 C++ 提交中击败了48.30%的用户
内存消耗 :9.7 MB, 在所有 C++ 提交中击败了74.11%的用户