二叉树
Binary Tree 二分树 二元树
二叉树的递归定义:或是空树,或是一棵由一个根结点和左右子树组成的树,且左右子树也是二叉树。
分枝结点:除叶结点以外的结点。
二叉树的性质
最多 2^h - 1 个结点
N2 = N0 - 1
满二叉树:所有分枝结点都存在左右子树,且叶结点都在同一层。
完全二叉树:除最后一层外,所有层的结点数都达到最大个数,且最后一层的结点都连续集中在最左边。
二叉查找树:左子树所有节点的值 < 根的值 < 右子树所有节点的值,且左右子树也是二叉查找树。
class Node {
public int data;
public Node left;
public Node right;
public Node(int data){
this.data = data;
this.left = null;
this.right = null;
}
}
class BinaryTree{
public Node root;
public BinaryTree(){
root = null;
}
public void insert(int data){ // 添加节点
Node node = new Node(data);
if(root == null){
root = node;
return;
}
Node curNode = root;
while(true){ // 直到找到空位置
if(data < curNode.data){ // 小于根找左子树
if(curNode.left == null){ // 有空位置就放入
curNode.left = node;
return;
}
else
curNode = curNode.left; // 移位
}
else{
if(curNode.right == null){
curNode.right = node;
return;
}
else
curNode = curNode.right; // 移位
}
}
}
public void inOrder(Node node){ // 中序遍历
if(node == null)
return;
inOrder(node.left); // 左
System.out.print(node.data + " "); // 根
inOrder(node.right); // 右
}
public void preOrder(Node node){ // 先序遍历
if(node == null)
return;
System.out.print(node.data + " "); // 根
preOrder(node.left); // 左
preOrder(node.right); // 右
}
public void postOrder(Node node){ //后序遍历
if(node == null)
return;
postOrder(node.left); // 左
postOrder(node.right); // 右
System.out.print(node.data + " "); // 根
}
}
public class Test {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
int[] a = {8,3,10,1,6,14,4,7,13};
for(int i=0;i<a.length;i++)
bt.insert(a[i]);
System.out.println("中序遍历(左根右)");
bt.inOrder(bt.root);
System.out.println();
System.out.println("先序遍历(根左右)");
bt.preOrder(bt.root);
System.out.println();
System.out.println("后序遍历(左右根)");
bt.postOrder(bt.root);
}
}
程序中数组对应的二叉查找树
中序遍历:左根右
1 3 4 6 7 8 10 13 14
先序遍历:根左右
8 3 1 6 4 7 10 14 13
后序遍历:左右根
1 4 7 6 3 13 14 10 8