Acc Non-recursive Java solution with queue


  • 0
    A
    public class Solution {
    public boolean hasPathSum(TreeNode root, int sum) {
        if (root==null) return false;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (queue.peek() != null) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
              TreeNode node = queue.poll();
              if ( node.val == sum && node.right == null && node.left == null) return true;
              if (node.left != null) {
                  node.left.val += node.val;
                  queue.add(node.left);
              }
              if (node.right != null) {
                  node.right.val += node.val;
                  queue.add(node.right);
              }
            }
        }
        return false;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.