首页 > 其他 > 详细

LeetCode: Sum Root to Leaf Numbers

时间:2014-02-04 10:32:10      阅读:440      评论:0      收藏:0      [点我收藏+]

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中如果想要一个基本类型作为引用传递的话,可以直接通过函数返回值表示。

bubuko.com,布布扣
 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     }
bubuko.com,布布扣

LeetCode: Sum Root to Leaf Numbers

原文:http://www.cnblogs.com/longhorn/p/3537749.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!