二叉树的构建(Java)

本文介绍如何使用Java构建二叉树,通过在每个节点的空指针设置为'#',根据前序遍历方式创建二叉树。内容包括具体思路、节点类的实现,并展示成功创建二叉树的前序遍历结果。
摘要由CSDN通过智能技术生成

二叉树的建立

思路

先对二叉树进行扩展,将每个节点的空指针设置为“#”,这样就可以按前序遍历的方式创建一个二叉树。

image

创建一个上图所示的二叉树。

输入的值为:A B D # # E # # C # #

实现:

//创建二叉树
public class Bshu {
    static int i=0;
    public static void main(String[] args) {

        Scanner scn = new Scanner(System.in);
        String s = scn.nextLine();
        String[] s1 = s.trim().split(" ");

        node root = new node();
        root = creat(root,s1);

        look(root);     //前序遍历
    }
        //递归创建
    public static node creat(node node,String[] s1){
        String temp = s1[i++];
        if(temp.equals("#")){
            return null;
        }else{
            node = new node(temp);
            node.leftchild = creat(node.leftchild,s1);
            node.rightchild = creat(node.rightchild,s1);
        }
        return node;
    }
    //前序遍历
    public static void look(node node){
        if(node!=null){
        System.out.print(node.data);
        look(node.leftchild);
        look(node.rightchild);
    }
    }
}

输出结果

A B D # # E # # C # # (回车)
ABDEC

可以看到,成功地输出二叉树的前序遍历结果,表示二叉树创建成功。

节点类
class node{
    String data;
    node leftchild;
    node rightchild;
    public node(String i,node left,node right){
        this.data = i;
        this.leftchild = left;
        this.rightchild = right;
    }
    public node(String s){
        this(s,null,null);
    }
    public node(){
    }
}
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值