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

Sum Root to Leaf Numbers

时间:2015-03-19 17:51:26      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/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.

解题思路:

比较典型的DFS+回溯,结合二叉树的遍历。这里递归要传入当前路径的和,以及总路径的和。但是由于java里面只能pass by value,而不能pass by reference,一般可以通过return一个值来解决。这里通过传入一个int[]的对象,就可以伪装成pass by reference了。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {        

int[] sum = new int[2]; dfs(root, sum); return sum[0]; } public void dfs(TreeNode root, int[] sum){ if(root == null){ return; } if(root.left == null && root.right == null){ sum[1] = sum[1] * 10 + root.val; sum[0] += sum[1]; sum[1] = sum[1] / 10; //重要,这里的回溯不能忘记 return; } sum[1] = sum[1] * 10 + root.val; dfs(root.left, sum); dfs(root.right, sum); sum[1] = sum[1] / 10; } }

本题还有另一种递归思路。一棵树的path sum,就是它左右子树的path sum。如此递归。

这里需要传入从root到当前节点的和,用以往后继续计算。特别要注意的,如果当前节点为null,应该返回0,而不是返回pathSum。因为看最后的递归返回,这代表当前子树的和为0。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
        return dfs(root, 0);
    }
    public int dfs(TreeNode root, int pathSum){
        if(root == null){
            return 0;   //不是return pathSum;
        }
        
        pathSum = pathSum * 10 + root.val;
        
        if(root.left == null && root.right == null){
            return pathSum;
        }
        return dfs(root.left, pathSum) + dfs(root.right, pathSum);
    }
}

 

Sum Root to Leaf Numbers

标签:

原文地址:http://www.cnblogs.com/NickyYe/p/4350918.html

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