二叉樹概念
1.除了最下面一層,每個節點都是父節點,每個節點都有且最多有兩個子節點;
2.除了嘴上面一層,每個節點是子節點,每個節點都會有一個父節點;
3.最上面一層的節點為根節點;
圖例說明:

中序遍歷概念
先打印左子樹(左子節點),接着打印父節點,最后打印右子樹(右子節點)
圖例說明:

最后貼代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
//創建二叉樹
function Node(data,left,right){
this.data = data;
this.left = left;
this.right = right;
}
Node.prototype.show = function(){
return this.data;
}
function BST(){
this.root = null;
}
BST.prototype.insert = function(data){
var node = new Node(data,null,null);
if(this.root == null){
this.root = node;
}else{
var current = this.root;
var parent;
while(true){
parent = current;
if(data < current.data){
current = current.left;
if(current == null){
parent.left = node;
break;
}
}else{
current = current.right;
if(current == null){
parent.right = node;
break;
}
}
}
}
}
//二叉樹中序遍歷
BST.prototype.inOrder = function(node){
if(node){
this.inOrder(node.left);
console.log(node.show() + " ");
this.inOrder(node.right);
}
}
//測試數據
var bst = new BST();
var nums = [10,3,18,2,4,13,21,9,8,9];
for(var i = 0;i < nums.length;i ++){
bst.insert(nums[i]);
}
bst.inOrder(bst.root);
</script>
</body>
</html>
