🎉 One-stop destination for all your technical interview Preparation 🎉
You are given the root of a binary tree containing digits from 0 to 9 only. Each root-to-leaf path in the tree represents a number.
Return the total sum of all root-to-leaf numbers. Test cases are generated so that the answer will fit in a 32-bit integer. A leaf node is a node with no children.
class Solution{
int ans = 0;
void dfs(TreeNode *root, int val){
if (!root) return;
val *= 10;
val += root->val;
if (root->left == NULL && root->right == NULL){
ans += val;
return;
}
dfs(root->left, val);
dfs(root->right, val);
}
public:
int sumNumbers(TreeNode *root){
if (!root) return 0;
dfs(root, 0);
return ans;
}
};
If you find more problems, please comment it below :)