今天又看了一遍樹的操作,發現二叉樹的先序遍歷,中序遍歷,後序遍歷的原理竟然如此簡單。雖然以前也會,但是今天找到了更簡單的方法。
溫故而知新,很好。
/**
* Created by BiuBiu_Jiao on 2018/3/31.
*/
//聲明一個節點
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;
this.inOrder = inOrder;
this.inOrderList = [];
this.preOrder = preOrder;
this.preOrderList = [];
this.afterOrder = afterOrder;
this.afterOrderList = [];
this.generateTree = generateTree;
}
//將一個數組,快速生成二叉樹
function generateTree(array) {
if(Array.isArray(array)){
for(let item of array){
this.inSert(item);
}
}
}
//插入節點
function inSert(data) {
var n = new Node(data,null,null);
if(this.root == null){
this.root = n;
}else{
//用兩個變量存儲root對象的指針,很靈活
var current = this.root;
var parent;
while (true){
parent = current;
if(data < current.data){
current = current.left;
if(current == null){
parent.left = n;
break;
}
//否則葉子節點就是父節點,在下一次循環的時候
}else if(data > current.data){
current = current.right;
if(current == null){
parent.right = n;
break;
}
}else{
//如果相等,就跳出循環
break;
}
}
}
}
//中序遍歷
var inOrderList = [];
function inOrder(node,that) {
if(node !== null){
inOrder(node.left,that);
// console.log(node.show()+" ");
that.inOrderList.push(node.show());
inOrder(node.right,that);
}
}
//前(先)序遍歷
function preOrder(node,that) {
if(!(node == null)){
// console.log(node.show() + " ");
that.preOrderList.push(node.show());
preOrder(node.left,that);
preOrder(node.right,that);
}
}
//後序遍歷
function afterOrder(node,that) {
if(!(node == null)){
afterOrder(node.left,that);
afterOrder(node.right,that);
that.afterOrderList.push(node.show());
// console.log(node.show() + " ");
}
}
var bst = new BST();
let array = [23,45,16,37,3,99,22];
array = [56,22,30,10,81,77,92];
bst.generateTree(array);
bst.inOrder(bst.root,bst);
console.log("inOrderList",bst.inOrderList.toString());
bst.preOrder(bst.root,bst);
console.log("preOrderList",bst.preOrderList.toString());
bst.afterOrder(bst.root,bst);
console.log("afterOrderList",bst.afterOrderList.toString());
結果:
inOrderList 10,22,30,56,77,81,92
preOrderList 56,22,10,30,81,77,92
afterOrderList 10,30,22,77,92,81,56
現在我們說說,溫故知新的新,究竟新在哪裏?
在此之前,我們要深刻理解,遞歸到底是什麼。
如果你有興趣的話,不妨再瞭解一下遞歸和迭代的區別。
先序遍歷
我們可以看到的是,打印節點的語句在最前面,所以這叫先序遍歷。
以此類推,中序遍歷、後序遍歷其實都有類似的結論。
中序遍歷,將打印當前節點的語句,放在中間。
後序遍歷,將打印當前節點的語句,放在最後。
//前(先)序遍歷
function preOrder(node,that) {
if(!(node == null)){
// console.log(node.show() + " ");
that.preOrderList.push(node.show());
preOrder(node.left,that);
preOrder(node.right,that);
}
}
PS:爲什麼要傳指針進去?
因爲這是遞歸調用,當在函數中自己調用自己的時候,沒有聲明這個方法是誰的(沒有用obj.method的方式調用)。因此我們需要將指針傳進去。
爲什麼不適用arguments.callee?
他並不能保證指針的指向是相同的。