[leetcode] 814. Binary Tree Pruning

Description

We are given the head node root of a binary tree, where additionally every node’s value is either a 0 or a 1.

Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.

(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)

Example 1:
Input: [1,null,0,0,1]
Output: [1,null,0,null,1]
 
Explanation: 
Only the red nodes satisfy the property "every subtree not containing a 1".
The diagram on the right represents the answer.

example1

Example 2:
Input: [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]

example2

Example 3:
Input: [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]

example3
Note:

  • The binary tree will have at most 100 nodes.
  • The value of each node will only be 0 or 1.

分析

题目的意思是:把不包含1的子树去除

一看是树的话,就是递归啦,这里的解决方案是用的或运算符,解法还是挺巧妙的。

  • 如果遍历到空节点,直接返回false,如果一个节点的左子树返回为0,说明,要么是空节点,要么是节点的值为0,则左子树可以直接置空,否则不剪枝;一个节点的右子树处理跟左子树一样;然后是当前节点的返回值,如果左右子树的返回值有一个为1或者当前的节点的值为1,则都返回1。

C++实现

/**
 * 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) {
        
        return solve(root) ? root: NULL;
    }
    bool solve(TreeNode* root){
        if(!root) return false;
        bool a1=solve(root->left);
        bool a2=solve(root->right);
        if(!a1) root->left=NULL;
        if(!a2) root->right=NULL;
        return root->val==1||a1||a2;
    }
};

Python实现

这三个条件:左子树为空,右子树为空,当前节点的值为 0,同时满足时,才表示以当前节点为根的原二叉树的所有节点都为 0,需要将这棵子树移除,返回空。有任一条件不满足时,当前节点不应该移除,返回当前节点。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pruneTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        root.left = self.pruneTree(root.left)
        root.right =self.pruneTree(root.right)
        if root.left is None and root.right is None and root.val==0:
            return None
        return root

参考文献

814. Binary Tree Pruning

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值