二叉树遍历
作者:互联网
package Tree;
import java.util.LinkedList;
import java.util.Queue;
public class BinaryTree {
int data;
BinaryTree lchild, rchild;
public static void main(String[] args) {
int[] a = new int[10];
for (int i = 0; i < 10; i++) a[i] = i;
BinaryTree t = new BinaryTree();
t = t.initTree(t, a);
t.preOrder(t);
System.out.println("");
t.inOrder(t);
System.out.println("");
t.postOrder(t);
}
//建立一完全二叉树
public BinaryTree initTree(BinaryTree t, int[] datas) {
//如果数组为空,返回空值
if (datas.length <= 0) return null;
//借助队列实现非递归赋值
Queue<BinaryTree> trees = new LinkedList<BinaryTree>();
//根节点入队
t.data = datas[0];
trees.add(t);
int index = 0;
while (index < datas.length - 2) {
BinaryTree tParrent = trees.poll();
if (++index <= datas.length) {
BinaryTree leftTree = new BinaryTree();
leftTree.data = datas[index];
tParrent.lchild = leftTree;
trees.offer(leftTree);
} else break;
if (++index <= datas.length) {
BinaryTree rightTree = new BinaryTree();
rightTree.data = datas[index];
tParrent.rchild = rightTree;
trees.offer(rightTree);
} else break;
}
return t;
}
public void preOrder(BinaryTree t) {
if (t != null) {
System.out.print(t.data);
preOrder(t.lchild);
preOrder(t.rchild);
}
}
public void inOrder(BinaryTree t) {
if (t != null) {
inOrder(t.lchild);
System.out.print(t.data);
inOrder(t.rchild);
}
}
public void postOrder(BinaryTree t) {
if (t != null) {
postOrder(t.lchild);
postOrder(t.rchild);
System.out.print(t.data);
}
}
}
标签:index,遍历,int,BinaryTree,二叉树,new,public,datas 来源: https://blog.csdn.net/modige_hm/article/details/120356628