题目描述
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.)
方法思路
class Solution {
//Runtime: 1 ms, faster than 100.00%
//Memory Usage: 36.8 MB, less than 66.67%
public TreeNode pruneTree(TreeNode root) {
if(root == null) return root;
if(!containsOne(root.left)) root.left = null;
if(!containsOne(root.right)) root.right = null;
pruneTree(root.left);
pruneTree(root.right);
return root;
}
public boolean containsOne(TreeNode root){
if(root == null)
return false;
if(root.left == null && root.right == null && root.val == 0)
return false;
if(root.val == 1)
return true;
return containsOne(root.left) || containsOne(root.right);
}
}