Node.js examples for Data Structure:Binary Tree
Binary Search Tree with push method
//node in tree// w ww. j ava2 s. com function Node(val) { this.value = val; this.left = null; this.right = null } //constructor for tree function BinarySearchTree() { this.root = null; } //the left values are small than the right values, and smaller than its parent node. There can only be two children per Node. //here is how to find the right position for BinarySearchTree.prototype.push = function(val) { var root = this.root; //if there is no root value, set the val to the new root and exit if(!root) { this.root = new Node(val); return; } var currentNode = root; var newNode = new Node(val); while(currentNode) { if(val < currentNode.value) { if(!currentNode.left) { currentNode.left = newNode; break; } else { currentNode = currentNode.left; } } else { if(!currentNode.right) { currentNode.right = newNode; break; } else { currentNode = currentNode.right; } } } } var bst = new BinarySearchTree(); bst.push(3); bst.push(2); bst.push(4); bst.push(7); bst.push(4); bst.push(9); bst.push(11); bst.push(1); bst.push(6); console.log(bst);