LeetCode 129: Sum Root to Leaf Numbers

/**
 * 129. Sum Root to Leaf Numbers
 * 1. Time:O(n)  Space:O(logn)
 * 2. Time:O(n)  Space:O(n)
 */

// 1. Time:O(n)  Space:O(logn)
class Solution {
    public int sumNumbers(TreeNode root) {
        return helper(root,0);
    }
    
    private int helper(TreeNode root, int i){
        if(root==null) return 0;
        int sum = i*10+root.val;
        if(root.left==null && root.right==null) return sum;
        return helper(root.left,sum)+helper(root.right,sum);
    }
}

// 2. Time:O(n)  Space:O(n)
class Solution {
    public int sumNumbers(TreeNode root) {
        int sum = 0;
        if(root==null) return sum;
        Stack<TreeNode> s1 = new Stack<>();
        Stack<Integer> s2 = new Stack<>();
        s1.push(root);
        s2.push(0);
        while(!s1.isEmpty()){
            TreeNode cur = s1.pop();
            int curSum = s2.pop()*10+cur.val;
            if(cur.left==null && cur.right==null)
                sum += curSum;
            if(cur.left!=null){
                s1.push(cur.left);
                s2.push(curSum);
            }
            if(cur.right!=null){
                s1.push(cur.right);
                s2.push(curSum);
            }
        }
        return sum;
    }
}
posted @ 2020-05-09 09:31  AAAmsl  阅读(60)  评论(0编辑  收藏  举报