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

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

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

问题

创建节点
class Node{
    int data;
    Node left;
    Node right;
    Node(int data){
        this.data = data;
        left = null;
        right = null;
    }
}
创建树
//创建树
class Tree{
    Node root = null;
    void insert(Node temp, int data){
        Node NewNode = new Node(data);
        if(temp == null){
             temp = NewNode;
        }
        else{
            if(data < temp.data){
                insert(temp.left, data);
            }
            else{
                insert(temp.right, data);
            }
        }
    }
}
主函数
public class test{
    public static void main(String[] args) {
        Tree t = new Tree();
        t.insert(t.root, 3);
        // t.insert(t.root,1);
        System.out.println(t.root.data);
    }
}

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

英文:

Creating the node

       
       class Node{
           int data;
           Node left;
           Node right;
           Node(int data){
                   this.data = data;
                   left = null;
                   right = null;
           }
       }

Creating the tree

        //create tree
        class Tree{
            Node root = null;
            void insert(Node temp, int data){
                Node NewNode = new Node(data);
                if(temp == null){
                     temp = NewNode;
                }
                else{
                    if(data&lt;temp.data){
                        insert(temp.left,data);
                    }
                    else{
                        insert(temp.right,data);
                    }
                }
            }
        }

Main function

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

> 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:

确定