在Java中构建二叉搜索树。无法确定空错误的原因。

huangapple 未分类评论60阅读模式
英文:

Building a Binary Search Tree in java. Unable to identify the reason for null error?

问题

  1. 创建节点
  1. class Node{
  2. int data;
  3. Node left;
  4. Node right;
  5. Node(int data){
  6. this.data = data;
  7. left = null;
  8. right = null;
  9. }
  10. }
  1. 创建树
  1. //创建树
  2. class Tree{
  3. Node root = null;
  4. void insert(Node temp, int data){
  5. Node NewNode = new Node(data);
  6. if(temp == null){
  7. temp = NewNode;
  8. }
  9. else{
  10. if(data < temp.data){
  11. insert(temp.left, data);
  12. }
  13. else{
  14. insert(temp.right, data);
  15. }
  16. }
  17. }
  18. }
  1. 主函数
  1. public class test{
  2. public static void main(String[] args) {
  3. Tree t = new Tree();
  4. t.insert(t.root, 3);
  5. // t.insert(t.root,1);
  6. System.out.println(t.root.data);
  7. }
  8. }

> 运行后我得到 t.root 为 null。我不明白为什么。需要一些帮助。
> 我将 t.root 传递为 temp,所以当 temp 被修改时,
> 这不意味着 t.root 也被修改了吗?

英文:

Creating the node

  1. class Node{
  2. int data;
  3. Node left;
  4. Node right;
  5. Node(int data){
  6. this.data = data;
  7. left = null;
  8. right = null;
  9. }
  10. }

Creating the tree

  1. //create tree
  2. class Tree{
  3. Node root = null;
  4. void insert(Node temp, int data){
  5. Node NewNode = new Node(data);
  6. if(temp == null){
  7. temp = NewNode;
  8. }
  9. else{
  10. if(data&lt;temp.data){
  11. insert(temp.left,data);
  12. }
  13. else{
  14. insert(temp.right,data);
  15. }
  16. }
  17. }
  18. }

Main function

  1. public class test{
  2. public static void main(String[] args) {
  3. Tree t = new Tree();
  4. t.insert(t.root,3);
  5. // t.insert(t.root,1);
  6. System.out.println(t.root.data);
  7. }
  8. }

> Upon running I get t.root is null. I don't understand why. Need some
> help.
> I am passing t.root as temp, so when temp gets modified
> doesn't that mean t.root does too?

huangapple
  • 本文由 发表于 2020年7月27日 13:51:16
  • 转载请务必保留本文链接:https://java.coder-hub.com/63109355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定