129. 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.

Hide Tags

TreeDepth-first Search

链接:  http://leetcode.com/problems/sum-root-to-leaf-numbers/

题解:

求二叉树路径和。依然是DFS,leaf的左右子节点均为空。

Time Complexity - O(n), Space Complexity - O(n)。                 -要看一下递归和尾递归的空间复杂度

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

Update:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
        return sumNumbers(root, 0);
    }
    
    private int sumNumbers(TreeNode root, int num) {
        if(root == null)
            return 0;
        int sum = num * 10 + root.val;
        if(root.left == null && root.right == null)
            return sum;
        return sumNumbers(root.left, sum) + sumNumbers(root.right, sum);
    }
}

二刷:

Java:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int sumNumbers(TreeNode root) {
        return sumNumbers(root, 0);
    }
    
    private int sumNumbers(TreeNode root, int sum) {
        if (root == null) return 0;
        sum = sum * 10 + root.val;
        if (root.left == null && root.right == null) return sum;
        else return sumNumbers(root.left, sum) + sumNumbers(root.right, sum); 
    }
}

Reference:

https://leetcode.com/discuss/20451/short-java-solution-recursion

原文地址:https://www.cnblogs.com/yrbbest/p/4438737.html