二叉树的构建(Java)

二叉树的建立

思路

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

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(){
    }
}

猜你喜欢

转载自blog.csdn.net/babylove_bale/article/details/78533828