05 August 2008
Given the
of a binary tree, return the same tree where every subtree (of the given tree) not containing a 1
root
has been removed.1
1
A subtree of a node
is 1
node
plus every node that is a descendant of 1
node
.1
node
Example 1:
1
2
3
4
5
Input: root = [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.
Example 2:
1
2
Input: root = [1,0,1,0,0,0,1]
Output: [1,null,1,null,1]
Example 3:
1
2
Input: root = [1,1,0,1,1,0,1,0]
Output: [1,1,0,1,1,null,1]
Constraints:
1
[1, 200]
.1
Node.val
is either 1
0
or 1
1
.1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
if (root == null) {
return root;
}
root.left = pruneTree(root.left); //null
root.right = pruneTree(root.right);
if (root.val == 1 || root.left != null || root.right != null) {
return root;
}
return null;
}
}