Leetcode 129: 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
.
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int SumNumbers(TreeNode root) { 12 var result = new int[1] {0}; 13 DFS(root, 0, result); 14 return result[0]; 15 } 16 17 private void DFS(TreeNode node, int cur, int[] result) 18 { 19 if (node == null) return; 20 21 if (node.left == null && node.right == null) 22 { 23 result[0] += cur + node.val; 24 } 25 26 if (node.left != null) DFS(node.left, (cur + node.val) * 10, result); 27 if (node.right != null) DFS(node.right, (cur + node.val) * 10, result); 28 } 29 }