Monday, December 31, 2018
814. Binary Tree Pruning
Version #2 DFS -> using null to represent false
47.32 %
class Solution {
public TreeNode pruneTree(TreeNode root) {
if (root == null) return null;
root.left = pruneTree(root.left);
root.right = pruneTree(root.right);
if (root.left == null && root.right == null && root.val == 0) return null;
return root;
}
}
Version #1 Typical DFS
5.28 %
class Solution {
public TreeNode pruneTree(TreeNode root) {
// recursively check if a node's left&right subtree containing 1
// if substree returns false, then set that subtree to null
// return dfs(left) || dfs(right) || node.val == 1
if (dfs(root)) return root;
return null;
}
private boolean dfs(TreeNode node) {
if (node == null) return false;
boolean left = dfs(node.left);
boolean right = dfs(node.right);
if (!left) {
node.left = null;
}
if (!right) {
node.right = null;
}
return left || right || node.val == 1;
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment