码迷,mamicode.com
首页 > 编程语言 > 详细

[LeetCode][Java] Sum Root to Leaf Numbers

时间:2015-07-29 19:19:56      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   sum root to leaf num   

题目:

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的数字元素,每一条从根节点到叶子节点的路径都可以代表一个数.

举个例子一条从根节点到叶子节点的路径为1->2->3 代表数为123.

找出所有的从根到叶子节点路径中所表示的数的和。

比如给定:

    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.

算法分析:

通过递归,思路比较清晰,主要就是考虑递归条件和结束条件。直接看代码,比较好理解。

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
 //又是递归
public class Solution 
{
    int sum = 0;
    public int sumNumbers(TreeNode root) 
    {
        if (root == null) return 0;
        run(root, 0);
        return sum;
    }
    public void run(TreeNode root, int num) 
    {
        num = 10 * num + root.val;
        if (root.left == null && root.right == null) 
            sum += num;
        if (root.left != null) 
            run(root.left, num);
        if (root.right != null)
            run(root.right, num);
    }
}</span>

版权声明:本文为博主原创文章,转载注明出处

[LeetCode][Java] Sum Root to Leaf Numbers

标签:leetcode   java   sum root to leaf num   

原文地址:http://blog.csdn.net/evan123mg/article/details/47131291

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