为二进制搜索树创建迭代插入物

问题描述 投票:0回答:1

嗨,我需要为给定的类Tree创建一个迭代插入方法;

public class Tree {
private int value ;
private Tree lhs ; // left child
private Tree rhs ; // right child
Tree ( int value ) {
this . value = value ;
}
...
}

My method looks like this:
public class Tree {
 private int value;
 private Tree lhs; // left child
 private Tree rhs; // right child
  Tree(int value) {
      this.value = value;
  }
  public void insert(int insertValue)
{
    while (this.value != null)
    {
        if(insertValue < value)
           if(this.lhs == null)
           {
             lhs = new Tree(insertValue);
              break;
             }
           else lhs = this.lhs;
       else
           if(this.rhs == null)
           {
              rhs = new Tree(insertValue);
             break;
            }
           else rhs = this.rhs;
   }
 }
}

编译器说:Tree.java:20:错误:二进制运算符'!='的操作数类型错误,而(this.value!= null)^触发类型:int第二种类型:1个错误也许有人可以帮助我修复它:)

java insert binary-search-tree
1个回答
0
投票

要在BST树中迭代插入节点,我们将需要使用两个指针遍历树。

public static TreeNode insertionIterative(TreeNode root, int value) {

    TreeNode current, parent;

    TreeNode tempNode = new TreeNode(value);

    if (root == null) {
        root = tempNode;
        return root;
    } else {
        current = root;
    }

    while (true) {
        parent = current;

        if (value < (int) current.data) {
            current = current.left;
            if (current == null) {
                parent.left = tempNode;
                return root;
            }

        } else if (value > (int) current.data) {
            current = current.right;

            if (current == null) {
                parent.right = tempNode;
                return root;
            }
        }

    }
}

编辑1:程序中的错误是value是一个基本类型int,而基本类型永远不能为null。因此,如@Jordan

所示,this.value!= null是无效的语句。

编辑2:关于为什么Java中的原语不能为null的原因,请参见this

要了解有关此错误的更多信息,请参见post

© www.soinside.com 2019 - 2024. All rights reserved.