递归二叉树插入

4

当我将节点添加到二叉树中并尝试显示有关它的信息时,信息没有显示出来。我认为我在递归插入算法中存在一些引用问题,但无法解决。

package test;

class BinaryTree<T> {
    private static class Node<T> {
        int key;
        T data;
        Node<T> leftChild;
        Node<T> rightChild;

        public Node(int key,T data) {
            this.key = key;
            this.data = data;
        }
    }

    public Node<T> rootNode;

    public BinaryTree() {
        rootNode = null;
    }

    public Node<T> getRootNode() {
        return rootNode;
    }

    // insert node into binary tree
    public void insertNode(int key,T data, Node<T> rootNode) {
        // to create new node

        // if tree doesn't have root elements
        if(rootNode == null) {
            rootNode = new Node<T>(key,data);
            rootNode.leftChild = null;
            rootNode.rightChild = null;
        }
        else {
            Node<T> focusNode = rootNode;

            if(key >= focusNode.key) {
                insertNode(key,data,focusNode.rightChild);
            }
            else {
                insertNode(key,data,focusNode.leftChild);
            }
        }
    }

    // inorder traverse tree
    public void inOrderTraverseTree(Node<T> focusNode) {
        if(focusNode != null) {
            inOrderTraverseTree(focusNode.leftChild);
            System.out.println(focusNode.data);
            inOrderTraverseTree(focusNode.rightChild);
        }
    }
}

public class MyApp {
    public static void main(String[] args) {
        BinaryTree<String> bintree = new BinaryTree<String>();
        bintree.insertNode(3, "Boss", bintree.rootNode);
        bintree.inOrderTraverseTree(bintree.rootNode);
    }
}

如果我使用这个算法添加节点并尝试显示信息,它是有效的。我该如何解决递归算法的问题?

public void addNode(int key, T name) {
        Node<T> newNode = new Node<T>(key,name);
        if(rootNode == null) {
            rootNode = newNode;
        }
        else {
            Node<T> focusNode = rootNode;
            Node<T> parent;
            while(true) {
                parent = focusNode;
                if(key < focusNode.key) {
                    focusNode = focusNode.leftChild;
                    if(focusNode == null) {
                        parent.leftChild = newNode;
                        return;
                    }
                }
                else {
                    focusNode = focusNode.rightChild;
                    if(focusNode == null) {
                        parent.rightChild = newNode;
                        return;
                    }
                }
            }
        }
    }

感谢您的任何帮助。
1个回答

3

浏览了您的代码后,我发现您正在检查null值的部分中,rootNode变量是函数内的局部变量。因此,您创建的新节点将在函数退出后立即被丢弃,它不会更改您的成员字段。

    // if tree doesn't have root elements
    if(rootNode == null) {
        rootNode = new Node<T>(key,data);
        rootNode.leftChild = null;
        rootNode.rightChild = null;
    }

您需要使用this.rootNode = new Node<T>(key,data);代替,或者使用不同的局部变量名以避免混淆。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接