129. Sum Root to Leaf Numbers

2020-03-17  本文已影响0人  7ccc099f4608

https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/

image.png

(图片来源https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/

日期 是否一次通过 comment
2020-03-16 0

递归

public int sumNumbers(TreeNode root) {

        return sum(root, 0);
    }

    public int sum(TreeNode root, int s){
        if(root == null) {
            return 0;
        }

        if(root.right == null && root.left == null) {
            return s*10 + root.val;
        }

        return sum(root.left, s*10 + root.val) + sum(root.right, s*10 + root.val);
    }
上一篇 下一篇

猜你喜欢

热点阅读