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


分析:


用递归解决,把左右子树的值加起来。

1. 递归结束条件:如果节点为叶子节点,返回到该节点的路径和

2. 分别计算左右子树的路径和,子树的路径和就是父节点的路径和*10加上该节点的值,最后返回坐子树的路径和加上右子树的路径和


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) {
        if(root==null)
            return 0;
        
        return helper(root, 0);
    }
    private int helper(TreeNode root, int num)
    {
        num = num*10+root.val;
        
        if(root.left == null && root.right==null)
            return num;
            
        int left = 0;
        int right =0;
        if(root.left!=null)
            left = helper(root.left, num);
        if(root.right!=null)
            right = helper(root.right, num);
        
        return left+right;
    }
    
}


你可能感兴趣的:(LeetCode,二叉树,leetcode,java,路径和)