将输入的数据存入二叉树,并采用前序遍历遍历该二叉树
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| function BinarySearchTree(){ this.root = null; } BinarySearchTree.prototype.push = function(val){ var root = this.root; 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; } } } } function Node(val){ this.value = val; this.left = null; this.right = null; } function preOrder(node) { if (node) { print(node.left); preOrder(node.value); preOrder(node.right); } }
|
http://khan4019.github.io/front-end-Interview-Questions/bst.html