LeetCode 129. Sum Root to Leaf Numbers
原题链接在这里:https://leetcode.com/problems/sum-root-to-leaf-numbers/
题目:
Given a binary tree containing digits from 0-9
only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path 1->2->3
which represents the number 123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path 1->2
represents the number 12
.
The root-to-leaf path 1->3
represents the number 13
.
Return the sum = 12 + 13 = 25
.
题解:
Top-down dfs到了叶子节点加值.
Time Complexity: O(n).
Space: O(h), h是树的高度.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int sumNumbers(TreeNode root) { 12 if(root == null){ 13 return 0; 14 } 15 16 int [] res = {0}; 17 dfs(root, 0, res); 18 return res[0]; 19 } 20 21 private void dfs(TreeNode root, int cur, int [] res){ 22 if(root == null){ 23 return; 24 } 25 26 cur = cur*10+root.val; 27 28 if(root.left == null && root.right == null){ 29 res[0] += cur; 30 return; 31 } 32 33 dfs(root.left, cur, res); 34 dfs(root.right, cur, res); 35 36 } 37 }
AC C++:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int sumNumbers(TreeNode* root) { 15 int res = 0; 16 dfs(root, 0, res); 17 return res; 18 } 19 20 private: 21 void dfs(TreeNode* root, int cur, int& res){ 22 if(!root){ 23 return; 24 } 25 26 cur = cur * 10 + root->val; 27 if(!root->left && !root->right){ 28 res += cur; 29 } 30 31 dfs(root->left, cur, res); 32 dfs(root->right, cur, res); 33 } 34 };
类似Path Sum II.