码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode]129. Sum Root to Leaf Numbers路径数字求和

时间:2018-01-26 10:57:53      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:+=   etc   body   numbers   pos   public   oid   col   color   

DFS的标准形式

用一个String记录路径,最后判断到叶子时加到结果上。

int res = 0;
    public int sumNumbers(TreeNode root) {
        if (root==null)
            return res;
        helper(root,"");
        return res;
    }
    public void helper(TreeNode root,String s)
    {
        s += root.val+"";
        if (root.left==null&&root.right==null)
        {
            res+=Integer.parseInt(s);
            return;
        }
        if (root.left!=null) helper(root.left,s);
        if (root.right!=null) helper(root.right,s);
    }

 

[LeetCode]129. Sum Root to Leaf Numbers路径数字求和

标签:+=   etc   body   numbers   pos   public   oid   col   color   

原文地址:https://www.cnblogs.com/stAr-1/p/8358036.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!