有序二叉树的创建

package com.qf.homework;

public class Demo1 {
    public static void main(String[] args) {
        String str = "java,python,iOS,bigdata,html,javascript,php,UI,goodgoodstudy,c,go,linkedHash,Set,TreeMap";
        TreeNode p = new TreeNode("1",new TreeNode("2",new TreeNode("3"),new TreeNode("4")),new TreeNode("5"));
        //precious(p);
//        inOrder(p);
//        after(p);

        TreeNode root = getTreeNode(str);
        precious(root);
    }
    public static TreeNode getTreeNode(String str){
        String[] words = str.split(",");
        TreeNode root = new TreeNode(words[0]);
        for (int i = 0; i < words.length; i++) {
            createBST(root,words[i]);
        }
        return root;
    }

    private static void createBST(TreeNode root, String word) {
        if (word.length() < root.val.length()){
            if (root.left == null) root.left = new TreeNode(word);
            else createBST(root.left,word);
        }else {
            if (root.right == null) root.right = new TreeNode(word);
            else createBST(root.right,word);
        }
    }

    //先序
    public static void precious(TreeNode root){
        if (root == null) return;
        if (root != null){
            System.out.println(root.val);
            precious(root.left);
            precious(root.right);
        }
    }
    //中序
    public static void inOrder(TreeNode root){
        if (root == null) return;
            inOrder(root.left);
            System.out.println(root.val);
            inOrder(root.right);
    }

    //后序
    public static void after(TreeNode root) {
        if (root == null) return;
        after(root.left);
        after(root.right);
        System.out.println(root.val);
    }

}


class TreeNode{
    String val;
    TreeNode left;
    TreeNode right;

    public TreeNode() {
    }

    public TreeNode(String val) {
        this.val = val;
    }

    public TreeNode(String val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }

    @Override
    public String toString() {
        return "TreeNode{" +
                "val=" + val +
                ", left=" + left +
                ", right=" + right +
                '}';
    }


}

谢谢观看!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值