二叉樹系列(1)-實現排序二叉樹

排序二叉樹就是在一棵普通的數的基礎上,一個節點的左節點的值一定小於這個節點的值,右節點的值大於這個節點的值。
每棵樹都是由節點生成的,每個節點都有左右節點兩個屬性,用JS來實現如下:

function  Node(data){
	this.data = data;
	this.left = null;
	this.right = null;
}

每棵樹都是由根節點構成,且樹本身需要一個插入的方法

function  BST(){
	this.root = null;
	this.insert = insert;
}

下面我們看看這個插入的方法該怎麼寫,
1、判斷根節點是否爲空,如果是,將新插入的節點設置爲根節點
2、拿需要插入的數據與根節點進行比較,如果大於根節點,取根節點的右節點node,否則取根節點的左節點node
3、判斷節點node是否爲空,如果爲空,將該節點的值設置爲插入值,否則將該節點視爲根節點,重複步驟1-3
具體的實現如下:

function  insert(data){
	let node = new Node(data);
	if(!this.root){
		this.root = node;
	}else{
		let parent = this.root;
		let currnet;
		while(true){
			current = parent;
			if( data > current.data ){
				parent= parent.right;
				if(!parent){
					current .right = node;
					break;
				}
			}else{
				parent= parent.left;
				if(!parent){
					current .left = node;
					break;
				}
			}
		}
	}
}

下面我們測試一下:

let  bst1 = new BST();
bst1.insert(3);
bst1.insert(5);
bst1.insert(2);
bst1.insert(1);
bst1.insert(4);
console.log(bst1);

得到如下結果
在這裏插入圖片描述

如此,就實現了一個排序二叉樹的數據結構了。
以上的insert方法有一點需要注意,遍歷的過程中,需要用cureent來保存當前節點,避免指針的丟失。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章