LeetCode: 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.


 

思路我觉得就是递归,如果遇到叶节点,返回叶节点的值,否则返回两个节点相加的结果。

注意的是,我本来想用一个全局的静态的值表示总和,但是在leetcode上测试的时候结果总是不对。

java中如果想要一个基本类型作为引用传递的话,可以直接通过函数返回值表示。

 1 public static int sumNumbers(TreeNode root) {
 2         if (root == null) return 0;
 3         return sum(root, 0);
 4     }
 5     public static int sum(TreeNode root, int cur) {
 6         if (root == null) return 0;
 7         
 8         cur = cur*10 + root.val;
 9         if (root.left == null && root.right == null){
10             return cur;
11         }
12         else {
13             return sum(root.left, cur) + sum(root.right, cur);
14         }
15     }

 

posted on 2014-02-04 03:31  longhorn  阅读(209)  评论(0编辑  收藏  举报

导航