结点:
function Node(data, left, right) {this.data = data;this.left = left;this.right = right;this.show = show;
}
显示树的数据:
function show(){return this.data;
}
二叉查找树:
// Binary Search Tree
function BST(){this.root = null;this.insert = insert;
}
添加结点到二叉树:
function insert(data){let n = new Node(data, null, null)if(this.root == null){this.root = n;}else{let current = this.root;let parent;while(true){parent = current;if(data < current.data){current = current.left;if(current == null){parent.left = n;breakk}}else{current = current.rightif(current == null){parent.right = n;break;}}}}
}
生成二叉查找树:
function genBST(list){if(list.length>0){let t = new BST();list.forEach((data)=>{t.insert(data);})return t}
}
let list = [2,3,4,1];
console.log(genBST(list));
先序遍历:
function DLR(t){if(t.root !== undefined){console.log(t.root.data);if(t.root.left !== null){DLR(t.root.left)}if(t.root.right!==null){DLR(t.root.right)}}else{if(t !== null){console.log(t.data);if(t.left !== null){DLR(t.left)}if(t.right!==null){DLR(t.right)}}}
}let list = [1,2,3,6,5,4];
let t = genBST(list);
DLR(t);
中序遍历:
function LDR(t){if(t.root !== undefined){if(t.root.left !==null){LDR(t.root.left)}console.log(t.root.data);if(t.root.right !== null){LDR(t.root.right)}}else{if(t !==null){if(t.left !== null){LDR(t.left);}console.log(t.data);if(t.right !== null){LDR(t.right);}}}
}let list = [1,2,3,6,5,4];
let t = genBST(list);
LDR(t);
后续遍历:
function LRD(t){if(t.root !== undefined){if(t.root.left !==null){LRD(t.root.left)}if(t.root.right !== null){LRD(t.root.right)}console.log(t.root.data);}else{if(t !==null){if(t.left !== null){LRD(t.left);}if(t.right !== null){LRD(t.right);}console.log(t.data);}}
}let list = [1,2,3,6,5,4];
let t = genBST(list);
LRD(t);
参考https://github.com/zoro-web/blog/issues/4