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;
}