樹
- 是計算機科學中常用到的一種數據結構。
- 是一種非線性的數據結構,以分層的方式存儲數據。
- 被用來存儲具有層級關係的數據。
二叉樹: 二叉樹是一種特殊的樹,對二叉樹進行查找非常快,爲二叉樹添加或刪除元素也非常快。
樹的定義
樹由一組以邊連接的節點組成,自上而下的層級順序。
一棵樹上最上面的節點稱爲根節點,如果一個節點下面連接多個節點,那麼該節點稱爲父節點,它下面的稱爲子節點。
一個節點可以有0個、1個或多個子節點。沒有子節點的節點稱爲葉子節點。
二叉樹的子節點個數不超過兩個
一個父節點的兩個子節點分別稱爲左節點和右節點。
二叉查找樹是一種特殊的二叉樹,相對較小的值存儲在左節點中,較大的值保存在右節點中。
二叉查找樹的構造函數
在二叉查找樹中,要執行 insert()
方法進行數據的插入。
遍歷二叉查找樹的方法有:中序,先序,後序
- 中序:按照節點上的鍵值,以升序訪問BST上的所有節點(左-根-右);
- 先序:先訪問根節點,然後以同樣方式訪問左子樹和右子樹(根-左-右);
- 後序:先訪問葉子節點,從左子樹到右子樹,再到根節點(左-右-根)。
構造函數如下:
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.preOrder = preOrder;
this.postOrder = postOrder;
}
function insert(data) {
var n = new Node(data, null, null);
if (this.root == null) {
this.root = null;
}
else {
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 {
current = current.right;
if (current == null) {
parent.right = n;
break;
}
}
}
}
}
// 中序遍歷,先遍歷左子樹
function inOrder(node) {
if (!(node == null)) {
inOrder(node.left);
putstr(node.show() + " ");
inOrder(node.right);
}
}
//先序遍歷
function preOrder() {
if (!(node == null)) {
putstr(node.show() + " ");
preOrder(node.left);
preOrder(node.right);
}
}
// 後序遍歷
function postOrder() {
if (!(node == null)) {
postOrder(node.left);
postOrder(node.right);
putstr(node.show() + " ");
}
}
/*
* 查找
**/
function getMin() {
var current = this.root;
while (!(current.left == null)) {
current = current.left;
}
return current.data;
}
function getMax() {
var current = this.root;
while (!(current.right == null)) {
current = current.right;
}
return current.data;
}
// 查找給定值
function find(data) {
var current = this.root;
while (current != null) {
if (current.data == data) {
return current;
}
else if (data < current.data) {
current = current.left;
}
else {
current = current.right;
}
}
return null;
}
function remove(data) {
root = removeNode(this.root, data);
}
function removeNode(node, data) {
if (node == null) {
return null;
}
if (data == node.data) {
// no subnode
if (node.left == null && node.right == null) {
return null;
}
// no left subnode
if (node.left == null) {
return node.right;
}
// no right subnode
if (node.right == null) {
return node.right;
}
// have two subnode
var tempNode = getSmallest(node.right);
node.data = tempNode.data;
node.right = removeNode(node.right, tempNode.data);
return node;
}
else if (data < node.data) {
node.left = removeNode(node.left, data);
return node;
}
else {
node.right = removeNode(node.right, data);
return node;
}
}
關於二叉查找樹,這片文章還不錯:https://segmentfault.com/a/1190000000740261