2 回答
TA贡献1891条经验 获得超3个赞
您永远不会更改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贡献1835条经验 获得超7个赞
如果使用递归呢?认识起来就更清楚了。
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;
}
}
}
添加回答
举报