我在理解下面的代碼時遇到問題。這是一個樹形數據結構,我不明白爲什麼我們需要兩個節點(父節點和focusnode
)在addnode()
方法中。我試圖用focusnode
這樣做,但它不起作用。我的想法是設置focusnode
爲根,並保持循環,直到focusnode
等於null
,並將focusnode
設置爲newnode
。樹數據結構addnode
public class tree {
node root;
public class node{
private int key;
private node left;
private node right;
node(int key){
this.key = key;
}
public int getkey(){
return key;
}
public node getleft(){
return left;
}
public node getright(){
return right;
}
}
public void addnode(int key){
node newnode = new node(key);
if(root == null){
root = newnode;
}else{
node focusnode = root;
node parent;
while(true){
parent = focusnode;
if(key < focusnode.key){
focusnode = focusnode.left;
if(focusnode == null){
parent.left = newnode;
return;
}
}else{
focusnode = focusnode.right;
if(focusnode == null){
parent.right = newnode;
return;
}
}
}
}
}
public void runnode(node focusnode){
if(focusnode != null){
runnode(focusnode.left);
runnode(focusnode.right);
System.out.println(focusnode.key);
}
}`
難道我們不能擺脫父母,並使用focusnode作爲參考? – user3725988
'focusnode'指向'.left' /'.right'節點。如果將'newnode'分配給'focusnode',那麼'focusnode'將不再引用'.left' /'.right'(當前爲'null'),而是引用您的'newnode'。但是如果我們記得'parent',那麼我們可以說'parent.left'並且改變了父節點的引用,即.left' /'.right',這就是樹結構所依賴的。分配給'focusnode'不會改變'parent.left'引用的內容。 –