二叉樹定義
二叉樹(BinaryTree)是n(n≥0)個結點的有限集,它或者是空集(n=0),或者由一個根結點及兩棵互不相交的、分別稱作這個根的左子樹和右子樹的二叉樹組成。
二叉樹有五種形態存在:
空集 - 有左子樹無右子樹 - 有右子樹無左子樹 - 有左右子樹 - 無左右子樹
滿二叉樹(FullBinaryTree)
一棵深度爲k且有2的k次方-1個結點的二又樹稱爲滿二叉樹。
滿二叉樹的特點:
(1) 每一層上的結點數都達到最大值。即對給定的高度,它是具有最多結點數的二叉樹。
(2) 滿二叉樹中不存在度數爲1的結點,每個分支結點均有兩棵高度相同的子樹,且樹葉都在最下一層上。
若一棵二叉樹至多隻有最下面的兩層上結點的度數可以小於2,並且最下一層上的結點都集中在該層最左邊的若干位置上,則此二叉樹稱爲完全二叉樹。
特點:
(1) 滿二叉樹是完全二叉樹,完全二叉樹不一定是滿二叉樹。
(2) 在滿二叉樹的最下一層上,從最右邊開始連續刪去若干結點後得到的二叉樹仍然是一棵完全二叉樹。
(3) 在完全二叉樹中,若某個結點沒有左孩子,則它一定沒有右孩子,即該結點必是葉結點。
完全二叉樹可以採用數組儲存,原因是可以通過數組下標推出其雙親和子節點。
用javascript表示
bintree.js
/**
* ------------------------------------------------------------------
* define the structure of bintree
* ------------------------------------------------------------------
*/
/**
* Node class
*
* @param {Node} left leftchild
* @param {Node} right rightchild
* @param {value} value value of the node
*
* @date 2014-11-4
* @author simonwoo
*/
function Node(left,right,value){
this.left = left;
this.right = right;
this.value = value;
}
Node.prototype.setLeft = function(left){
this.left = left;
}
Node.prototype.setRight = function(right){
this.right = right;
}
Node.prototype.getvalue = function(){
return this.value;
}
/**
* BinTree class
*
* @param {Node} root root node of the tree
*
* @date 2014-11-4
* @author simonwoo
*/
function BinTree(root){
this.root = root;
}
//前序遍歷
BinTree.prototype.preorder = function(node){
if(node==null)return;
console.log(' ' + node.value + ' ');
this.preorder(node.left);
this.preorder(node.right);
}
//中序遍歷
BinTree.prototype.inorder = function(node){
if(node==null)return;
this.inorder(node.left);
console.log(' ' + node.value + ' ');
this.inorder(node.right);
}
//後序遍歷
BinTree.prototype.postorder = function(node){
if(node==null)return;
this.postorder(node.left);
this.postorder(node.right);
console.log(' ' + node.value + ' ');
}
index.html
表示下面這棵二叉樹
<!doctype html>
<html>
<!--head-->
<head>
<meta charset="utf-8">
<title>bintree</title>
</head>
<!--body-->
<body>
</body>
<script src = 'bintree.js'></script>
<script type="text/javascript">
var node1 = new Node(null,null,1);
var node2 = new Node(null,null,2);
var node3 = new Node(null,null,3);
var node4 = new Node(null,null,4);
var node5 = new Node(null,null,5);
var node6 = new Node(null,null,6);
var node7 = new Node(null,null,7);
//set the relations
node1.setLeft(node2);
node1.setRight(node3);
node2.setLeft(node4);
node2.setRight(node5);
node3.setLeft(node6);
node3.setRight(node7);
var bt = new BinTree(node1);
bt.preorder(bt.root);
bt.inorder(bt.root);
bt.postorder(bt.root);
</script>
</html>