Insufficient Nodes in Root to Leaf Paths
给一个二叉树和一个limit, 返回删除二叉树路径上的节点加和小于limit的所有节点后的二叉树.
class Solution {
public TreeNode sufficientSubset(TreeNode root, int limit) {
if (helper(root, 0, limit)) {
return null;
}
return root;
}
private boolean helper(TreeNode root, int sum, int limit) {
if (root.left == null && root.right == null) {
if(sum + root.val < limit)
return true;
else
return false;
}
boolean left = true;
boolean right = true;
if (root.left != null) {
left = helper(root.left, sum + root.val, limit);
}
if (root.right != null) {
right = helper(root.right, sum + root.val, limit);
}
if (left) {
root.left = null;
}
if (right) {
root.right = null;
}
return left && right;
}
}