LeetCode 129 Sum Root to Leaf Numbers DFS
阿新 • • 發佈:2022-05-16
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); } };