二叉搜索树的建立和排序

二叉搜索树的建立和排序

今天面了一家自研,有一道二叉搜索树的题目,但是自己做的不好
就是有几个学生和成绩,使用树来存储
左子树大于等于root,右节点小于root

package org.example;

public class Main {
    public static void main(String[] args) {
        TreeNode root = new TreeNode("Bill", 70);//这样可以
        Solution sol = new Solution();
        sol.insert_r(root,new TreeNode("Peter",80));
        sol.insert_r(root,new TreeNode("Jack",90));
        sol.insert_r(root,new TreeNode("Carl",80));
        sol.insert_r(root,new TreeNode("Steven",85));
        sol.insert_r(root,new TreeNode("Tom",60));

        sol.showTopThree(root);


    }



}



package org.example;

import java.util.HashSet;
import java.util.Set;

public class Solution {

    public void insert_r(TreeNode root,TreeNode p){
        if(p.score>=root.score){
            if(root.left==null){
                root.left=new TreeNode(p.name,p.score);
            }else{
                insert_r(root.left,p);
            }
        }else{
            if(root.right==null){
                root.right=new TreeNode(p.name,p.score);
            }else{
                insert_r(root.right,p);
            }
        }
    }

    public void insert(TreeNode root, TreeNode p){

    }


    public void showTopThree(TreeNode root){
        if(root==null) {
            System.out.println("该树为空!!");
            return;
        }
        Set<Integer> set=new HashSet<>();
        orderForShow(root,set);
    }

    public void orderForShow(TreeNode node,Set<Integer> set){
        if(node==null)return;

        orderForShow(node.left,set);
        if(set.size()<=3){
            set.add(node.score);
            if(set.size()<=3){
                System.out.println("name:"+node.name+"score:"+node.score);
            }
        }

        orderForShow(node.right,set);
    }



}

package org.example;

public class TreeNode{
        public String name;
        public int score;
        public TreeNode left;
        public TreeNode right;

    public TreeNode() {
    }

    public TreeNode(String name, int score) {
            this.name = name;
            this.score = score;
        }


    }

在树的建立过程中,我犯了错误
此外关于值传递哪里我也犯了错误

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值