gpt4 book ai didi

java - 在 BST 中插入元素时出现 NullPointerException

转载 作者:行者123 更新时间:2023-11-30 05:35:51 24 4
gpt4 key购买 nike

我正在尝试使用迭代方法在二叉搜索树中插入元素,但我收到 NullPointerException 并且我无法弄清楚为什么会出现此错误。我尝试更改循环并检查温度,但我不明白那里发生了什么问题。编辑:-我已经添加了整个代码。

     import java.util.*;
import java.io.*;

class Node {
Node left;
Node right;
int data;

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

class Solution {

public static void preOrder(Node root) {

if (root == null)
return;

System.out.print(root.data + " ");
preOrder(root.left);
preOrder(root.right);

}

/* Node is defined as :
class Node
int data;
Node left;
Node right;

*/

public static Node insert(Node root, int data) {

Node inserter = new Node(data);
Node temp = root;
while (true) {
if (inserter.data <= temp.data) {
if (temp.left == null) {
temp.left = inserter;
break;
} else
temp = temp.left;

} else {
if (temp.right == null) {
temp.right = inserter;
break;
} else
temp = temp.right;

}
}

return root;
}

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
Node root = null;
while (t-- > 0) {
int data = scan.nextInt();
root = insert(root, data);
}
scan.close();
preOrder(root);
}
}

最佳答案

public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int t = scan.nextInt();
Node root = null;
while (t-- > 0) {
int data = scan.nextInt();
root = insert(root, data);
}
scan.close();
preOrder(root);
}

在 main 方法中,您传递 root == null

您需要重写您的插入方法然后它才会起作用

public static Node insert(Node root, int data) {

// check if root == null then initialize root and return it
if(root == null){
return new Node(data);
}
//--------

Node inserter = new Node(data);
Node temp = root;
while (true) {
if (inserter.data <= temp.data) {
if (temp.left == null) {
temp.left = inserter;
break;
} else
temp = temp.left;

} else {
if (temp.right == null) {
temp.right = inserter;
break;
} else
temp = temp.right;

}
}

return root;
}

关于java - 在 BST 中插入元素时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56643885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com