2 回答

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
您永遠(yuǎn)不會(huì)更改lc和rc鏈接。嘗試這樣的事情:
if(newnode.key <= n.key)
{
if(n.lc==null){n.lc = newnode; break;}
n = n.lc;
System.out.println("left");
}
else
{
if(n.rc==null){n.rc = newnode; break;}
n = n.rc;
System.out.println("right");
}

TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
如果使用遞歸呢?認(rèn)識(shí)起來就更清楚了。
public final class BinaryTree {
private static final boolean ADD_TO_PARENT = true;
private static final boolean ALREADY_ADDED = false;
private Node root;
public void add(int key, String value) {
Node node = new Node(key, value);
if (add(node, root) == ADD_TO_PARENT)
root = node;
}
private static boolean add(Node node, Node parent) {
if (parent == null)
return ADD_TO_PARENT;
if (node.key <= parent.key) {
if (add(node, parent.left) == ADD_TO_PARENT)
parent.left = node;
} else if (add(node, parent.right) == ADD_TO_PARENT)
parent.right = node;
return ALREADY_ADDED;
}
public static final class Node {
private final int key;
private final String value;
private Node left;
private Node right;
public Node(int key, String value) {
this.key = key;
this.value = value;
}
@Override
public String toString() {
return value + " is " + key;
}
}
}
添加回答
舉報(bào)