Leetcode112.Path Sum

作者: Stan95 | 来源:发表于2018-04-04 13:34 被阅读8次

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.


    Approach1: DFS


    This problem is quite similar to the LeetCode104, I use two stacks, one for node and one for node value. This is a pre-order idea to process nodes. Each time when I process the node, I process the value of it and update the sum of it. Cause the problem is asked about the root-leaf. I thought a valid path is right. that's the mistake I made at first. So I need to check if the node has child even if the value is equal to sum.
    class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null) return false;
            Stack<TreeNode> stack = new Stack<>();
            Stack<Integer> value = new Stack<>();
            stack.push(root);
            value.push(root.val);
            while(!stack.empty()){
                TreeNode node = stack.pop();
                int temp = value.pop();
                if(temp == sum && node.left == null && node.right == null) {//follow up may exist here
                    return true;
                }
                if(node.left != null){
                    stack.push(node.left);
                    value.push(node.left.val + temp);
                }
                if(node.right != null){
                    stack.push(node.right);
                    value.push(node.right.val + temp);
                }     
            }
            return false;
        }
    }
    
    Follow up question my be like: Find a valid path is fine, no need to root-leaf. Then just remove the condition "node.left == null && node.right == null".

    Approach2 Recursion


    The basic idea is to subtract the value of current node from sum until it reaches a leaf node and the subtraction equals 0, then we know that we got a hit. Otherwise the subtraction at the end could not be 0. Recursion pattern goes like update the parameter while call it self.
     class Solution {
        public boolean hasPathSum(TreeNode root, int sum) {
            if(root == null) return false;
        
            if(root.left == null && root.right == null && sum - root.val == 0) return true;
        
            return hasPathSum(root.left, sum - root.val) || hasPathSum(root.right, sum - root.val);
        }
    }

    相关文章

      网友评论

        本文标题:Leetcode112.Path Sum

        本文链接:https://www.haomeiwen.com/subject/unykhftx.html