leetcode-sum root to leaf numbers

来源:互联网 发布:nt数据看宝宝男女最准 编辑:程序博客网 时间:2024/06/06 13:19

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.

public class Solution {    int result=0;    public int sumNumbers(TreeNode root) {        if(root==null)return result;        mySum(root,0);        return result;    }    public void mySum(TreeNode root,int value){        int cur=10*value+root.val;        if(root.left==null&&root.right==null)result+=cur;        if(root.right!=null)mySum(root.right,cur);        if(root.left!=null)mySum(root.left,cur);    }}
树的问题很多都是层遍历,由上到下,由下到上。由下到上的就要在上面接受下面返回来的数值,由上到下就简单一些,数值一步一步传下去,然后在最底层判断结束条件做相应的处理。

这道题目需要用由上到下的想法,因为涉及到一个值传递到两个分支中,同时需要对层数有所了解。

需要注意的是结束条件:

当左子树和右子树都是null的时候才能加入这个值。

0 0
原创粉丝点击