Skip to content

Instantly share code, notes, and snippets.

@jinwolf
Created January 30, 2016 15:49
Show Gist options
  • Select an option

  • Save jinwolf/596bdb3c1e71d165abc9 to your computer and use it in GitHub Desktop.

Select an option

Save jinwolf/596bdb3c1e71d165abc9 to your computer and use it in GitHub Desktop.
breadth first search binary tree in JavaScript
function TreeNode(value) {
this.value = value;
this.left = null;
this.right = null;
}
var root = new TreeNode(15);
root.left = new TreeNode(7);
root.right = new TreeNode(26);
root.left.left = new TreeNode(1);
root.left.right = new TreeNode(11);
root.left.left.right = new TreeNode(3);
root.right.left = new TreeNode(22);
root.right.right = new TreeNode(30);
root.right.right.right = new TreeNode(32);
root.right.right.right.left = new TreeNode(31);
root.right.right.right.right = new TreeNode(33);
function traverse(root) {
var queue = [];
queue.push(root);
while(queue.length > 0) {
var node = queue.shift();
// print the value
console.log(node.value);
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
}
traverse(root);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment