1 回答

TA貢獻1995條經驗 獲得超2個贊
你有幾個問題。
在下面的代碼中查看我的評論。
if (root.value < node.value) {
if (node.right == null) {
root.right = new Node(node.value);
log.info("node.right.value:" + root.right.value);
}
} else { //<--- delete the right(}) curly brace.
// because your else clause is in the wrong place
log.info("insert(node.right):" + root.right.value);
insert(root.right);
}
}
正如我在評論中所說,您需要停止使用root
進行比較。不會更改root
以反映遞歸調用中的節點更改。所以你一遍又一遍地替換相同的值。
更新答案從這里開始。
這是我在保持代碼不變方面所能做的最好的事情。主要問題是您一遍又一遍地使用相同的 root 值。所以我添加了一個插入方法,它同時獲取了根和節點。我不會這樣做的。這就是我會做的。
首先通過
values
,而不是nodes
插入方法。制作一個
second insert method
需要 anode
和的 avalue
。如果 the
root
為 null,則創建 anode with the value
并分配它。insert(node, value)
否則,根據需要遞歸調用using left 或 right。如果null
,則創建一個具有值的新節點并分配它。
這是你的修改版本。我還添加了一個靜態打印例程。
public class TreeDemo {
public static void main(String[] args) {
Tree t = new Tree();
t.insert(new Node(-1));
t.insert(new Node(5));
t.insert(new Node(8));
t.insert(new Node(-10));
t.insert(new Node(4));
t.insert(new Node(-3));
t.insert(new Node(9));
t.insert(new Node(12));
print(t.root);
}
public static void print(Node n) {
if (n.left != null) {
print(n.left);
}
// print inorder
System.out.println(n.value);
if (n.right != null) {
print(n.right);
}
}
}
class Node {
Node left = null;
Node right = null;
float value = 0;
public Node(float value) {
this.value = value;
left = null;
right = null;
}
}
class Tree {
Node root;
public Tree() {
root = null;
}
public void insert(Node node) {
if (root == null) {
root = node;
return;
}
insert(root, node);
}
// added this method
private void insert(Node troot, Node node) {
if (troot.value > node.value) {
if (troot.left == null) {
troot.left = node;
}
else {
insert(troot.left, node);
}
}
else {
if (troot.value <= node.value) {
if (troot.right == null) {
troot.right = node;
}
else {
insert(troot.right, node);
}
}
}
}
}
添加回答
舉報