我在Java中找到了一个二叉树的代码:
public class Tree {
Node root;
Node curr;
public void addNode(int n){
Node temp=new Node(n);
if (root==null){
root=temp;
}
else{
curr=root;
while(curr!=null){
System.out.println("current element "+curr.elem);
if (temp.elem>curr.elem){
curr=curr.right;
if (curr==null){
System.out.println("added right branch element "+temp.elem);
root.der=temp;
}
}
else{
curr=curr.left;
if (curr==null){
root.left=temp;
}
}
}
}
}
}
public class Node {
int e;
Node left;
Node right;
public Nodo (int n){
e=n;
left=null;
right=null;
}
}
public static void main(String[] args) {
// TODO code application logic here
Tree t=new Tree();
t.addNode(5);
t.addNode(10);
t.addNode(20);
t.addNode(50);
}
我添加了一些打印行来查看它的内部工作,但我遇到的问题是为什么打印此代码的数据是:
current element 5
added right branch element 10
current element 5
current element 10
added right branch element 20
current element 5
current element 20
added right branch element 50
current element 5
current element 50
added right branch element 100
我的意思是为什么它会在 while 循环中跳转并且不打印内部元素?例如,在插入数字 50 时,我想它应该打印:
current element 5
current element 10
current element 20
但没有直接从 5 到 20,这是为什么呢?还有一行写着:
root.der=temp 或 root.left=temp;这是否意味着每次添加新节点时所有树都被视为一个大节点?
谢谢