LeetCode 814. Binary Tree Pruning
原题链接在这里:https://leetcode.com/problems/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.
Example 2: Input: [1,0,1,0,0,0,1] Output: [1,null,1,null,1]
Example 3: Input: [1,1,0,1,1,0,1,0] Output: [1,1,0,1,1,null,1]
Note:
- The binary tree will have at most
100 nodes
. - The value of each node will only be
0
or1
.
题解:
DFS from bottom.
If root == null, return null.
Check left and right.
If left != null or right != null or root.val == 1, this means its subtree containing itself has at least 1, return root.
Otherwise, return null.
Time Complexity: O(n).
Space: O(h).
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public TreeNode pruneTree(TreeNode root) { 18 if(root == null){ 19 return root; 20 } 21 22 root.left = pruneTree(root.left); 23 root.right = pruneTree(root.right); 24 if(root.val == 1 || root.left != null || root.right != null){ 25 return root; 26 } 27 28 return null; 29 } 30 }