leetcode 814. Binary Tree Pruning(修剪二叉树)

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.
在这里插入图片描述
把节点全是0的子树删掉

思路:
在遍历的过程中删掉全是0的子树

刚开始想把子树传入,当值全是0时设置root为null,但是发现通过参数把root传入,在函数中把root=null后,函数外面它还是存在的,如下面这样测试了一下,发现结果是not null。

	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(2);

		setNull(root.left);
		if(root.left == null) {
			System.out.println("null");
		} else {
			System.out.println("not null");
		}
	}
	
	static void setNull(TreeNode root) {
		root = null;
	}

所以只能判断子树中是否有1,没有1的话设置子树为null
而且不能看见1就返回true,还要遍历下去,把没有1的子树都删掉
注意root也是判断的对象,root是0,子树都是0,那么连root也要删掉

    public TreeNode pruneTree(TreeNode root) {
        if(root == null) return null;
        if(!hasOne(root)) root = null;
        return root;
    }
    
    boolean hasOne(TreeNode root) {
        if(root == null) return false;
        boolean leftOne = hasOne(root.left);
        boolean rightOne = hasOne(root.right);
        
        if(!leftOne) root.left = null;
        if(!rightOne) root.right = null;
        
        if(leftOne || rightOne || root.val == 1) return true;
                
        return false;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

蓝羽飞鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值