【问题标题】:In order traversal of a trinary search tree为了遍历三叉搜索树
【发布时间】:2014-10-13 05:24:32
【问题描述】:

所以,我有以下代码在三叉搜索树中插入一个元素(左树较小,中树相同,右树较大)

public void insert (TrinaryTree<T> root, T data) {
    //if the given tree doesn't exist yet
    if (root == null){
        root = new TrinaryTree<T>(data);
    }
    //if the given value is greater, insert to the right
    else if (root.getData().compareTo(data) > 0){
        insert (root.right, data);
    }
    //if the given value is equal, insert to the mid
    else if (root.getData().compareTo(data) == 0) {
        insert (root.mid, data);
    }
    //if the given value is less, insert to the left
    else {
        insert (root.left, data);
    }
}

然后我尝试打印出我的树(以便遍历检查我所做的事情是否正确 -

public void inorderTraversal (TrinaryTree<T> root){
    if (root != null){
        inorderTraversal(root.getLeft());
        System.out.println(root.getData());
        inorderTraversal(root.getRight());      
    }
}

现在当我尝试运行主类时,就是这样 -

public static void main (String [] args) {
    TrinaryTree<Integer> tree = new TrinaryTree<Integer>(5);
    tree.insert(tree, 4);
    tree.insert(tree, 9);
    tree.insert(tree, 5);
    tree.insert(tree, 7);
    tree.insert(tree, 2);
    tree.insert(tree, 2);       
    tree.inorderTraversal(tree);
}

我刚得到输出 5。我发现是因为主树的左右子树为空。我不确定为什么会这样。我的插入函数有效,因为我在插入函数中放入了一条打印语句,并且该语句确实被打印了。为什么子树仍然为空?

【问题讨论】:

    标签: java algorithm tree binary-search-tree


    【解决方案1】:

    insert的代码!一旦你用 null 值调用它(你想把东西放在左边或右边),那么很可能一切都是空的。

    • root.leftroot.right (可能)为空,您的代码不会 将新创建的节点添加到上一级节点。
    • 您调用 compareTo 的值可能为 null(否 NPE?)

    最重要的是,当您使用未初始化的值(左或右)调用 insert 时,您的代码将创建一个 TrinaryTree 节点,但它无法将其添加到它的父节点(您可能打算这样做),并且新创建的节点将在方法调用后进行垃圾收集。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-09
      • 2011-09-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多