Given a binary tree containing digits from0-9
Only, each root-to-leaf path cocould represent a number.
An example is the root-to-leaf path1->2->3
Which represents the number123
.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path1->2
Represents the number12
.
The root-to-leaf path1->3
Represents the number13
.
Return the sum = 12 + 13 =25
.
Given a binary tree containing only 0-9 numbers, each root-to-leaf path can represent a number.
An example of Root-to-leaf path1->2->3
Represents 123.
Find the sum of all root-to-leaf numbers.
The thought is that the depth first traversal.
public int sumNumbers(TreeNode root) {return dfs(root, 0);}public int dfs(TreeNode root, int sum) {if (root == null)return 0;sum = sum * 10 + root.val;if (root.left == null && root.right == null)return sum;return dfs(root.left, sum) + dfs(root.right, sum);}// Definition for binary treepublic class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}