二叉树排序 (递归遍历) 遍历

package week3.day10;
/**
 * 2020/8/3
 * 15:08
 * zmx
 */
public class TestBinarySortTree {
    public static void main(String[] args) {
        BinarySortTree tree=new BinarySortTree();
        //添加元素
        tree.add(10);
        tree.add(5);
        tree.add(20);
        tree.add(25);
        tree.add(30);
        tree.add(30);
        tree.add(30);
        System.out.println(tree.size);
        tree.Nodeprint();
    }
}
class BinarySortTree{
    private Node root;
    private int value;
    public int size=0;
    public void add(int value){
        if(this.root==null){
            this.root=new Node(value);//添加根节点
            size++;
        }
        else {
                boolean b=this.root.addChild(value);//添加子节点
                System.out.println(b);
            }
    }

    public void Nodeprint(){
        root.print();
    }

    class Node{
        private int v;
        private Node left;
        private Node right;
        public Node(int v) {
            this.v = v;
        }
        public boolean addChild(int value) {

            if (this.v>value){
                if (this.left!=null) {
                    return this.left.addChild(value);//
                }
                else{
                    this.left=new Node(value);//左节点为空,添加子节点
                    System.out.println(value+"在 " +this.v+"的左边");
                }
            }
            else if(this.v<value){
                if(this.right!=null){
                    return this.right.addChild(value);//
                }
               else {
                    this.right = new Node(value);//添加右节点
                    System.out.println(value + "在 " + this.v + "的右边");
                }
            }
            else {
                System.out.println("重复元素");
                return false;
            }
            return true;
        }
        public void print(){//中序遍历
            if (this.left!=null){
                this.left.print();
            }
            System.out.println(this.v);
            if (this.right!=null){
                this.right.print();
            }

        }
    }
}

当有重复元素添加时,最深层的addChild会直接向上层返回false,上层再往上侧,最后最高层函数结果为false;如果不用return结束掉当前结束方法,虽然最底层返回结果为false,但上层方法中肯定会有一个返回true的。(能从上层下来,就必然会有true的)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值