算法——二叉排序树的建立中序遍历

【1】代码:

①Node节点

package algorithm.tree.binarySortTree_BST;

public class Node {
    int val;
    Node left;
    Node right;

    public Node(int val) {
        this.val = val;
    }

    @Override
    public String toString() {
        return val+"";
    }
    public void add(Node node){
        if(node == null)
            return;
        if (node.val<this.val){
            if (this.left == null){
                this.left = node;
            }else{
                //向左递归添加
                this.left.add(node);
            }
        }else{
            if (this.right == null){
                this.right = node;
            }else{
                //右节点不为空就递归添加
                this.right.add(node);
            }
        }
    }
}


②BST binarySortTree二叉排序树:

package algorithm.tree.binarySortTree_BST;

public class BTS {
    //根节点
    Node root;

    //添加
    public void add(Node n){
        if (root == null){
            root = n;
        }else{
            root.add(n);
        }
    }
    //给外部中序遍历的接口
    public void show(){
        midOrder(root);
    }
    //中序遍历
    private void midOrder(Node n){
        //左边
        if (n == null)
            return;
        if (n.left != null){
            midOrder(n.left);
        }
        //打印
        System.out.println(n);
        //右边
        if (n.right != null){
            midOrder(n.right);
        }
    }

}


③ 测试代码:

package algorithm.tree.binarySortTree_BST;

public class Test {
    public static void main(String[] args) {
        int[] arr = {4, 6, 2, 12, 45, 5, 123, 6, 2};
        BTS tree = new BTS();
        for (int t:arr) {
            tree.add(new Node(t));
        }
        tree.show();
    }
}

【2】测试结果:

  1. 待测试数据:
    在这里插入图片描述
  2. 结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值