0

二分木のツリートラバーサルをコーディングすることを学んでいます。これまでのところ、ネット上の多くのチュートリアルからこれを思いつきました。ただし、トラバーサルを行おうとすると、無限ループに陥ります。どこが間違っていますか?

class Node {
int value;
String name;

Node lchild = null;
Node rchild = null;

Node(int key, String name) {
    this.value = key;
    this.name = name;
    }
}

public class genTrees {

Node root;

public void addNode(int key, String s) {
    Node newnode = new Node(key, s);
    if (root == null) {
        System.out.println("Added Root");
        root = newnode;
    } else {
        Node focusNode = root;
        Node parent;
        while (true) {
            parent = focusNode;
            if (key <= focusNode.value) {
                focusNode = focusNode.lchild;
                if (focusNode == null) {
                    System.out.println("Added on Left" + key);
                    parent.lchild = newnode;
                    return; // All done
                }
            }
            if (key > focusNode.value) {
                focusNode = focusNode.rchild;
                if (focusNode == null) {
                    System.out.println("Added on Right" + key);
                    parent.rchild = newnode;
                    return;
                }
            }
        }
    }
}

void inOrder(Node n) {
    while (n != null) {
        inOrder(n.lchild);
        System.out.println(n);
        inOrder(n.rchild);
    }
}

ありがとう!

4

1 に答える 1