您的位置:首页 > 其它

生成二叉排序树并先序遍历、中序遍历、后序遍历

2015-07-08 11:12 246 查看
1、新建BinaryTree.java文件定义二叉树结构:

public class BinaryTree {
private int data;
private BinaryTree left;
private BinaryTree right;
public BinaryTree(int data){
this.data = data;
this.left = null;
this.right = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public BinaryTree getLeft() {
return left;
}
public void setLeft(BinaryTree left) {
this.left = left;
}
public BinaryTree getRight() {
return right;
}
public void setRight(BinaryTree right) {
this.right = right;
}

}


2、新建操作类BinaryTreePreorder.java,插入方法:

public static void insert(BinaryTree root, int data){
if(data > root.getData()){
if(root.getRight() == null){
root.setRight(new BinaryTree(data));
}else{
insert(root.getRight(), data);
}
}else{
if(root.getLeft() == null){
root.setLeft(new BinaryTree(data));
}else{
insert(root.getLeft(), data);
}
}
}


3、遍历方法:

/**
* 先序遍历
* @param root
*/
public static void preOrder(BinaryTree root){
if(root == null){
return;
}
//遍历出数据
System.out.print(root.getData() + "-");
if(root.getLeft() != null){
preOrder(root.getLeft());
}
if(root.getRight() != null){
preOrder(root.getRight());
}
}

/**
* 中序遍历
* @param root
*/
public static void inOrder(BinaryTree root){
if(root == null){
return;
}
if(root.getLeft() != null){
preOrder(root.getLeft());
}
//遍历出数据
System.out.print(root.getData() + "-");
if(root.getRight() != null){
preOrder(root.getRight());
}
}

/**
* 后序遍历
* @param root
*/
public static void suffixOrder(BinaryTree root){
if(root == null){
return;
}
if(root.getLeft() != null){
preOrder(root.getLeft());
}
if(root.getRight() != null){
preOrder(root.getRight());
}
//遍历出数据
System.out.print(root.getData() + "-");
}


4、测试

public static void main(String[] str) {
int[] array = { 36, 10, 35, 66, 16, 18, 90, 76, 9, 20 };
BinaryTree root = new BinaryTree(array[0]); // 创建二叉树
for (int i = 1; i < array.length; i++) {
insert(root, array[i]); // 向二叉树中插入数据
}
System.out.println("先根遍历:");
preOrder(root);
System.out.println();
System.out.println("中根遍历:");
inOrder(root);
System.out.println();
System.out.println("后根遍历:");
suffixOrder(root);
}


测试结果:

先根遍历:
36-10-9-35-16-18-20-66-90-76-
中根遍历:
10-9-35-16-18-20-36-66-90-76-
后根遍历:
10-9-35-16-18-20-66-90-76-36-
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: