java 基本二叉树实现

二叉树的实现:

      //传入值
        boot.date=temp.charAt(0);
      //传入左子树
        boot.lson=maketree(temp.charAt(0)+" 的左子树");
      //传入右子树
        boot.rson=maketree(temp.charAt(0)+" 的右子树");
        return boot; 

这三句是关键语句 运用递归算法把maketree返回的tree 赋值给两边子树;

import java.util.Scanner;

public class Tree {
    Tree lson;
    Tree rson;
    char date;
//二叉树创建
    public Tree maketree(String s){
        Scanner sc=new Scanner(System.in);
        System.out.println(s);
        String temp=sc.next();
      //判断输入停止
        if(temp.charAt(0)<'A') return null;
        Tree boot=new Tree();
      //传入值
        boot.date=temp.charAt(0);
      //传入左子树
        boot.lson=maketree(temp.charAt(0)+" 的左子树");
      //传入右子树
        boot.rson=maketree(temp.charAt(0)+" 的右子树");
        return boot;
    }
//中序遍历
    public void show(Tree tree){
        if(tree!=null){
//左
            show(tree.lson);
//根
            System.out.println(tree.date);
//右
            show(tree.rson);
        }
    }
}
class test{
    public static void main(String[] args) {
        Tree t=new Tree();
        t.show(t.maketree("根"));
    }
}

猜你喜欢

转载自blog.csdn.net/joob000/article/details/81202057