Sum Root to Leaf Numbers

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);

    }

}

 

你可能感兴趣的:(number)