Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

156
Views
BST preorder traversal question. why am I getting the wrong answer using queue? javascript

I'm using queue to iteratively solve a BST preorder traversal question. I know for stack, it's reversed and it works, but with queue I'm getting the wrong answer. Why? Thanks

var preorderTraversal = function(root) {
   if (root == null) {
     return [];
   }

   const queue = [];
   const result = [];

   queue.unshift(root);

   while(queue.length > 0) {
     let current = queue.shift();
     result.unshift(current.val);

     if (current.right) queue.unshift(current.right);
     if (current.left) queue.unshift(current.left);
   }

   return result;
};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are using queue as a stack, since you shift values in and out at one and the same side of the array, which is what a stack does ("LIFO (last in, first out)"). So it actually works, but as you state at the start, it works in reverse because you prepend the values to the result. If you would append them, it would be fine:

var preorderTraversal = function(root) {
   if (root == null) {
     return [];
   }

   const queue = [];
   const result = [];

   queue.unshift(root);

   while(queue.length > 0) {
     let current = queue.shift();
     result.push(current.val); // Append instead of prepend

     if (current.right) queue.unshift(current.right);
     if (current.left) queue.unshift(current.left);
   }

   return result;
};

// Add the Node class to facilitating creating a binary tree (a binary search tree)
class Node {
    constructor(val) {
        this.val = val;
        this.left = this.right = null;
    }
    add(val) {
        if (val < this.val) {
            if (this.left) this.left.add(val);
            else this.left = new Node(val);
        } else {
            if (this.right) this.right.add(val);
            else this.right = new Node(val);
        }
    }
    print(tab="") {
        if (this.right) this.right.print("  " + tab);
        console.log(tab + this.val);
        if (this.left) this.left.print("  " + tab);
    }
}

// Demo
let root = new Node(4);
for (let val of [2, 6, 1, 3, 5, 7]) root.add(val);
console.log("The tree (with root at the far left): ");
root.print(); // Print the tree
console.log("preorder traversal: ", ...preorderTraversal(root));

Again, this is a stack solution, not a queue solution -- despite the variable name. JavaScript array methods give a "deque" interface to arrays, and so you can easily add and remove elements from either side of the array.

If you exclusively use push and pop you'll have a stack behaviour, and if you replace those with unshift and shift, you'll still have a stack behaviour.

You'll get a queue behaviour when you use the pair push/shift or the pair unshift/pop, but that will not be useful for implementing a pre order traversal. That is what you would use for a level order (breadth-first) traversal.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!