LeetCode 129 Sum Root to Leaf Numbers DFS
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.
For example, the root-to-leaf path 1 -> 2 -> 3
represents the number 123
.
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.
Solution
还是利用 \(DFS\):用另一个参数 \(cur\) 表示当前的值,对于 \(cur\) 的更新:
\[cur = 10\cdot cur+root.val
\]
如果到达叶子节点,则直接返回 \(cur\). 最后对左右子树分别递归即可:
\[\text{dfs}(root.right,cur)+\text{dfs}(root.left,cur)
\]
点击查看代码
/**
* 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 {
private:
int dfs(TreeNode* root, int ans){
if(!root) return 0;
ans = ans*10 + root->val;
if(!root->left && !root->right)return ans;
return dfs(root->left, ans)+dfs(root->right,ans);
}
public:
int sumNumbers(TreeNode* root) {
if(root==NULL) return 0;
return dfs(root, 0);
}
};