javascript实现二叉树的原理:
function Node(data, left, right){
this.data = data;
this.left = left;
this.right = right
this.show = show;
}
function show(){
return this.data
}
function BST(){
this.root = null;
this.insert = insert;
}
function insert(data){
var newNode = new Node(data, null, null);
if (this.root == null){
this.root = newNode;
} else {
var current = this.root;
var parent;
while (true){
parent = current;
if (current.data > data ){
current = current.left;
if (current == null){
parent.left = newNode;
break;
}
} else {
current = current.right;
if (current == null){
parent.right = newNode;
break;
}
}
}
}
}
function inOrder(node){
if (node){
inOrder(node.left);
console.log(node.data);
inOrder(node.right);
}
}
function preOrder(node){
if (node){
console.log(node.data);
preOrder(node.left);
preOrder(node.right);
}
}
function postOrder(node){
if (node){
postOrder(node.left);
postOrder(node.right);
console.log(node.data);
}
}
var bst = new BST();
bst.insert(23);
bst.insert(122);
bst.insert(112);
bst.insert(123);
bst.insert(12);
bst.insert(2);
bst.insert(10);
console.log('中序遍历:');
inOrder(bst.root);
console.log('先序遍历:');
preOrder(bst.root);
console.log('后序遍历:');
postOrder(bst.root);
用js二叉树实现的demo
https://shaojinghong.github.io/js-DataStructure/