原题链接在这里: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 }
类似Path Sum II.