码迷,mamicode.com
首页 > 其他好文 > 详细

Sum Root to Leaf Numbers——LeetCode

时间:2015-04-06 00:54:29      阅读:189      评论: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.

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.

 

题目大意:给一个二叉树,每个节点都是0-9之间的数字,从根节点到叶结点表示一个数字,求所有的这些数字的和。

解题思路:这道题应该是考察DFS,可以直接DFS求解,或者中序遍历用queue也可以做,最近做题没什么状态,脑袋一团浆糊。

    public int sumNumbers(TreeNode root) {
        return sum(root,0);
    }
    
    public int sum(TreeNode node,int sum){
        if(node==null){
            return 0;
        }
        if(node.left==null&&node.right==null){
            sum=sum*10+node.val;
            return sum;
        }
           return  sum(node.left,sum*10+node.val)+sum(node.right,sum*10+node.val);
    }

 

Sum Root to Leaf Numbers——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4395029.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!