二叉搜索树的建立和排序
今天面了一家自研,有一道二叉搜索树的题目,但是自己做的不好
就是有几个学生和成绩,使用树来存储
左子树大于等于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;}}
在树的建立过程中,我犯了错误
此外关于值传递哪里我也犯了错误