Leetcode 1022. Sum of Root To Leaf Binary Numbers
Given a binary tree where each node contains a single digit (0 or 1), each path from the root to a leaf represents a binary number. You need to find the sum of these binary numbers represented by all paths from the root to the leaves.
[1, 1000]
.0
or 1
.Here is the Java code to solve the problem:
/**
* 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;
* }
* }
*/
public class Solution {
public int sumRootToLeaf(TreeNode root) {
return dfs(root, 0);
}
private int dfs(TreeNode node, int currentSum) {
if (node == null) {
return 0;
}
currentSum = (currentSum << 1) | node.val;
if (node.left == null && node.right == null) {
return currentSum;
}
return dfs(node.left, currentSum) + dfs(node.right, currentSum);
}
}
currentSum
to the left by 1 bit (currentSum << 1
), then add the value of the current node (node.val
).null
, return 0 since it does not contribute to any path.null
, it means we have reached a leaf node. Return the currentSum
.dfs
method on the left and right children of the current node.N
is the number of nodes in the tree. Each node is visited exactly once.H
is the height of the tree. This space is used by the recursion stack. In the worst case, H = N (skewed tree), and in the best case, H = log(N) (balanced tree).Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?