Tuesday, October 28, 2014

Path Sum LeetCode

Recursion:
public boolean hasPathSum(TreeNode root, int sum) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        if (root == null) return false;
        if (root.left == null && root.right == null && sum == root.val) {
            return true;
        } else {
            return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
        }
       
    }

Non-recursion:
public boolean hasPathSum(TreeNode root, int sum) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
       if (root==null) return false;
     
       Queue<TreeNode> nodeQueue = new LinkedList<TreeNode>();
       Queue<Integer> intQueue = new LinkedList<Integer>();
       nodeQueue.add(root);
       intQueue.add(root.val);
     
       while (!nodeQueue.isEmpty()) {
           TreeNode currNode = nodeQueue.poll();
           int currVal = intQueue.poll();
         
           if (currNode.left == null && currNode.right == null && sum == currVal) {
               return true;
           }
           if (currNode.left != null) {
               nodeQueue.add(currNode.left);
               intQueue.add(currVal + currNode.left.val);
           }
           if (currNode.right != null) {
               nodeQueue.add(currNode.right);
               intQueue.add(currVal + currNode.right.val);
           }
       }
       return false;
     
    }

No comments:

Post a Comment