leetcode Sum Root to Leaf Numbers

来源:互联网 发布:java单例模式添加数据 编辑:程序博客网 时间:2024/06/14 13:36

题目链接

思路:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int result;    public int sumNumbers(TreeNode root) {        if(root==null)        {            return 0;        }        help(root, 0);        return result;    }    public void help(TreeNode root,int sum)    {        sum=sum*10+root.val;        if(root.left==null&&root.right==null)        {            result+=sum;            return;        }        if(root.left!=null)        {            help(root.left,sum);        }        if(root.right!=null)        {            help(root.right, sum);        }    }}
0 0
原创粉丝点击