创建一个二叉树,并使用先序遍历

import java.util.Scanner;
//定义一个二叉树
//实例化后,形成二叉树的节点
class Tree{
  //定义节点的属性
    private char data;//存储数据
    //存储左右子树地址的属性
    private Tree left,right;
    //控制数组索引
    private int top;//默认为0
    /**
     *  创建一颗二叉树,并返回根节点地址
     * @param des
     * @return
     */
    public Tree create(String des){

        Scanner sc=new Scanner(System.in);
        System.out.println("des:"+des);
              String str=sc.next();
        if(str.charAt(0)<'A')return null;

        //实例化一个tree的节点
        Tree root=new Tree();
         //为当前的节点赋值
         root.data=str.charAt(0);
        //在当前树根的基础上通过递归创建左右子 树
         root.left=create(str.charAt(0)+" 左子树:");
         root.right=create(str.charAt(0)+" 右子树:");
        //返回创建的二叉树的树根
        return root;
    }
    //二叉树的遍历,先序遍历、中序遍历和后序遍历
    public void show(Tree tree){
        //先序遍历
        if(tree!=null){
            System.out.println(tree.data);
            //遍历左子树
            show(tree.left);
            show(tree.right);
        }
    }
}
public class Demo02 {
    public static void main(String[] args) {
          Tree tree=new Tree();
        Tree root=tree.create("根");
          //调用遍历
        tree.show(root);
    }
}

 

posted @ 2018-07-25 20:45  张明洋  阅读(365)  评论(0编辑  收藏  举报