每一个节点
package tree;
/**
* @author wangpei
* @version
*创建时间:2017年3月5日 上午11:10:34
* 树节点
*/
public class TreeNode {
protected char data;
protected TreeNode Lchild;
protected TreeNode Rchild;
public TreeNode(char data){
this.data=data;
}
public char getData() {
return data;
}
public void setData(char data) {
this.data = data;
}
public TreeNode getLchild() {
return Lchild;
}
public void setLchild(TreeNode lchild) {
Lchild = lchild;
}
public TreeNode getRchild() {
return Rchild;
}
public void setRchild(TreeNode rchild) {
Rchild = rchild;
}
}
树节点:
package tree;
/**
* @author wangpei
* @version
*创建时间:2017年3月5日 上午11:11:54
* 递归树节点遍历(先,中,后)
*/
public class TreeExercise {
protected TreeNode root; // 树的根节点
protected int size; // 树长度
protected char[] data; // 树的数据
public TreeExercise(char[] data) {
this.data = data;
size = data.length;
root = createTree(0);
}
public TreeNode createTree(int index) { // 采用递归生成二叉树
if (index >= size)
return null;
if (data[index] == '0')
return null;
TreeNode node = new TreeNode(data[index]);
node.setLchild(createTree(2 * index + 1));
node.setRchild(createTree(2 * index + 2));
return node;
}
/*先序递归遍历二叉树*/
public void PrintOrder(TreeNode root){
if(root!=null){
System.out.print(root.getData()+"..");
PrintOrder(root.Lchild);
PrintOrder(root.Rchild);
}
}
/*中序遍历二叉树*/
public void InOrder(TreeNode root){
if(root!=null){
InOrder(root.Lchild);
System.out.print(root.getData()+"..");
InOrder(root.Rchild);
}
}
/*后续遍历二叉树*/
public void PostOrder(TreeNode root){
if(root!=null){
PostOrder(root.Lchild);
PostOrder(root.Rchild);
System.out.print(root.data+"..");
}
}
/*输出二叉树的值*/
public static void print(TreeNode root){
System.out.println(root.data);
}
public static void main(String[] args) {
char[] chars = new char[] {'A', 'B', 'C', '0', 'D', 'E', 'F','0','0','G','0','0','0','H','0'};
TreeExercise ec=new TreeExercise(chars);
ec.PostOrder(ec.getRoot());
// System.out.println(ec.getRoot().data);
// System.out.println(root.Lchild.data);
}
public TreeNode getRoot() {
return root;
}
public void setRoot(TreeNode root) {
this.root = root;
}
}