129. Sum Root to Leaf Numbers

2022/4/12 6:12:29

本文主要是介绍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);
    }
}

 



这篇关于129. Sum Root to Leaf Numbers的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程