其他分享
首页 > 其他分享> > 129. Sum Root to Leaf Numbers

129. Sum Root to Leaf Numbers

作者:互联网

My first solution:

class Solution {
    private int sum =0;
    public int sumNumbers(TreeNode root) {
        preOrder(root, "");
        return sum;
    }
    
    private void preOrder(TreeNode root, String numString){
        if(root==null)
            return;
        if(root.left==null&&root.right==null){
            int num = Integer.valueOf(numString+root.val);
            sum+=num;
            return;
        }
        preOrder(root.left, numString+root.val);
        preOrder(root.right, numString+root.val);
    }
}

My second solution:

class Solution {
    private int sum =0;
    public int sumNumbers(TreeNode root) {
        preOrder(root, 0);
        return sum;
    }
    
    private void preOrder(TreeNode root, int num){
        if(root==null)
            return;
        if(root.left==null&&root.right==null){
            sum+=num*10+root.val;
            return;
        }
        preOrder(root.left, num*10+root.val);
        preOrder(root.right, num*10+root.val);
    }
}

 

标签:preOrder,val,int,root,Sum,num,129,null,Root
来源: https://www.cnblogs.com/feiflytech/p/16133362.html