Last Updated on 2022-09-19 by Clay
Problem
You are given the root of a binary tree where each node has a 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. The test cases are generated so that the answer fits in a 32-bits integer.
Constraints:
- The number of nodes in the tree is in the range
[1, 1000]
. Node.val
is0
or1
.
Solution
Since every route has to go to the bottom, the first impression is to use recursion to do DFS.
Just remember that you need to multiply the current value by 2 in each recursive function. Because each time you add a new value, the old binary value will become longer.
C++ Sample Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int DFS(TreeNode* root, int ans) {
// Base case
if (!root) return 0;
// Compute the current value
ans = ans * 2 + root->val;
// The recursive reach the endpoint
if (!root->left && !root->right) return ans;
// Return
return DFS(root->left, ans) + DFS(root->right, ans);
}
int sumRootToLeaf(TreeNode* root) {
return DFS(root, 0);
}
};
Python Sample Code
class Solution:
def DFS(self, root, ans):
# Base case
if not root: return 0
# Compute the current value
ans = ans * 2 + root.val
# If reach the recursive endpoint
if not root.left and not root.right: return ans
# Return
return self.DFS(root.left, ans) + self.DFS(root.right, ans)
def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
return self.DFS(root, 0)