leetcode No1022. Sum of Root To Leaf Binary Numbers
Welcom to follow Dufre/LeetCode
Question
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit. For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
Return the sum of these numbers.
Example 1:
Input: [1,0,1,0,1,0,1]
Output: 22
Explanation: (100) + (101) + (110) + (111) = 4 + 5 + 6 + 7 = 22
Note:
The number of nodes in the tree is between 1 and 1000.
node.val is 0 or 1.
The answer will not exceed 2^31 - 1.
Solution
Key Point
- DFS
- Recursion(record curSum)
For example: 110
The result is: 1×(2^2) + 1×(2^1) + 0×(2^0).
- Step 1: current node is 1, curSum = 1×2
- Step 2: current node is 1, curSum = 2×(1×2)+1,
- Step 3: current node is 0, curSum = 2×(2×(1×2)+1)+0 = 1×(2^2) + 1×(2^1) + 0×(2^0)
So the law is f(x) = 2×f(x-1)+node.val
Code
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int res = 0;
public int sumRootToLeaf(TreeNode root) {
int curSum = 0;
helper(root, curSum);
return res;
}
void helper(TreeNode root, int curSum){
if (root == null){
return;
}
curSum = curSum*2 + root.val;
if (root.left == root.right){
res += curSum;
return;
}
helper(root.left, curSum);
helper(root.right, curSum);
}
}
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
res = 0
def helper(self, root: TreeNode, curSum):
if root is None:
return
curSum = curSum*2 + root.val
if root.left is None and root.right is None:
self.res = self.res + curSum
self.helper(root.left, curSum)
self.helper(root.right, curSum)
def sumRootToLeaf(self, root: TreeNode) -> int:
curSum = 0
self.helper(root, curSum)
return self.res
C/C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sumRootToLeaf(TreeNode* root) {
int res = 0;
int curSum = 0;
helper(root, curSum, res);
return res;
}
void helper(TreeNode* root, int curSum, int &res){
if (root == NULL){
return;
}
curSum = curSum*2 + root->val;
if (root->left == root->right){
res += curSum;
return;
}
helper(root->left, curSum, res);
helper(root->right, curSum, res);
}
};