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

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);
    }

 

posted @ 2018-01-26 09:04  stAr_1  阅读(131)  评论(0编辑  收藏  举报