LeetCode 112: Path Sum

/**
 * 112. Path Sum
 * 1. Time:O(n)  Space:O(h)
 * 2. Time:O(n)  Space:O(h)
 */

// 1. Time:O(n)  Space:O(h)
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null) return false;
        if(root.left==null && root.right==null)
            return sum==root.val;
        return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
    }
}

// 2. Time:O(n)  Space:O(h)
class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null) return false;
        Stack<TreeNode> nodeStack = new Stack<>();
        Stack<Integer> sumStack = new Stack<>();
        nodeStack.push(root);
        sumStack.push(sum-root.val);
        while(!nodeStack.isEmpty()){
            TreeNode node = nodeStack.pop();
            int curSum = sumStack.pop();
            if(node.left==null && node.right==null&&curSum==0)
                return true;
            if(node.left!=null){
                nodeStack.push(node.left);
                sumStack.push(curSum-node.left.val);
            }
            if(node.right!=null){
                nodeStack.push(node.right);
                sumStack.push(curSum-node.right.val);
            }
        }
        return false;
    }
}
posted @ 2020-05-08 11:12  AAAmsl  阅读(65)  评论(0编辑  收藏  举报