1.基本概念:
树(Tree)
树是n(n>=0)个节点的有限集T,n=0,T为空树,n>0时候,(1)有且仅有一个称为T的根的结点, (2)当n>1时,余下的结点分为m(m>0)个互不相交的有限集T1,T2,...,Tm ,每个Ti(1≤i≤m)也是一棵树,且称为根的子树。
二叉树
二叉数最多只有两个子树,分别是左子树,和右子树.
2.遍历二叉树
D----访问根结点,输出根结点
L-----递归遍历左二叉树
R-----递归遍历右二叉树
DLR
LDR
LRD
3.java代码实现
public class TreeBinary {
// the root of tree
private Node root;
public TreeBinary(int data) {
if (root == null) {
root = new Node(0);
root.data = data;
root.left = null;
root.right = null;
}
}
public TreeBinary() {
// TODO Auto-generated constructor stub
}
// insert the value of node
public void insert(int i) {
root = insert(root, i);
}
public Node insert(Node node, int data) {
if (node == null) {
node = new Node(data);
} else if (data <= node.data) {
// 插入左子树
node.left = insert(node.left, data);
} else {
// 插入右子树
node.right = insert(node.right, data);
}
return node;
}
// create the three by passing the array
public void buildTree(int[] data) {
for (int i = 0; i < data.length; i++) {
insert(data[i]);
}
}
public void printTree() {
printTree(root);
}
public void printTree(Node node) {
if (node == null)
return;
// left, node itself, right
System.out.print(node.data + " ");
printTree(node.left);
printTree(node.right);
}
public static void main(String[] args) {
TreeBinary biTree=new TreeBinary();
int[] data={2,1,3,6,4};
biTree.buildTree(data);
biTree.printTree();
}
}
class Node {
public Node(int i) {
this.data = i;
}
public Node left;
public Node right;
public int data;
}