用JAVA面向对象的思维的来定义一个二叉树类,通过键盘输入生成二叉树,并编写方法实现对二叉树节点的遍历输出。

先是构建二叉树以及三种遍历的函数,采用左小右大的方法。

 class BinaryTree {
    Node root;    //根节点
    public void addNode(int value){
        Node newNode = new Node(value);
        if(root == null){
        root = newNode;
        }
        else{
            Node temp = root;
            while(temp!=null){
                if(value<=temp.data){
                    if(temp.left==null){
                        temp.left = newNode;
                        return;
                    }else
                        temp = temp.left;
                }else{
                    if(temp.right==null){
                        temp.right = newNode;
                        return;
                    }else
                        temp = temp.right;
                }
            }
        }
    }
    /**
     *
     * @param root
     */
    //中序遍历
    public void midprint(Node root){
        if(root!=null){
        midprint(root.left);
        System.out.print(root.data + " ");
        midprint(root.right);
        }
    }
    //后序遍历
     public void posprint(Node root){
        if(root!=null){
        posprint(root.left);
        posprint(root.right);
        System.out.print(root.data + " ");
        }
    }  
    //前序遍历
     public void preprint(Node root){
        if(root!=null){
        System.out.print(root.data + " ");
        preprint(root.left);
        preprint(root.right);
        }
    }    
}

创建一个新结构。

class Node{
    int data;      //当前节点数值
    Node left;     //左孩子
    Node right;    //右孩子
    public Node(int data){
    this.left = null;
    this.right = null;
    this.data = data;
    }
}

主函数如下:

    public static void main(String[] args) {
        // TODO code application logic here
        BinaryTree b = new BinaryTree();
        System.out.println("请输入几个数并用逗号隔开(如:5,3,6,...):");
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        String[] arr  = str.split(",");
        int[] c = new int[arr.length];
        for(int j = 0; j<c.length;j++) {
         c[j] = Integer.parseInt(arr[j]);
        }
        for(int j = 0; j<c.length;j++) {
         b.addNode(c[j]);
        }
        System.out.print("前序遍历:");
        b.preprint(b.root);
        System.out.println();
        System.out.print("中序遍历:");
        b.midprint(b.root);
        System.out.println();
        System.out.print("后序遍历:");
        b.posprint(b.root);
    }

运行的结果如下:

 

  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值