【问题标题】:java Binary search tree insertion recursion seem to always return null rootjava二叉搜索树插入递归似乎总是返回空根
【发布时间】:2021-07-04 15:10:40
【问题描述】:

您好,我目前正在尝试使用一些在线参考构建 Java BST,但在插入过程中遇到问题,因为我意识到在尝试执行 inOrder 遍历后它不会创建树,经过一些尝试后我发现了问题将根传递到我的插入方法时。

我的节点类:

public class TreeNode
{
    String m_key;
    Object m_value;
    TreeNode m_left;
    TreeNode m_right;
    
    //constructor
    public TreeNode(String inKey, Object inVal)
    {
        if(inKey==null)
        {
            throw new IllegalArgumentException("Key cannot be null.");
        }
        
        m_key = inKey;
        m_value = inVal;
        m_left = null;
        m_right = null;
    }
}

我的插入方法:

public void insert(String key, Object data)
{
    m_root = insertRec(m_root, key, data);
}

private TreeNode insertRec(TreeNode x, String key, Object val)
{
    if(x == null)
    { 
        x = new TreeNode(key,val);
    }
    
    int cmp = key.compareTo(x.m_key);
    if(cmp<0)
    {
        x.m_left = insertRec(x.m_left, key, val);
    }
    else if(cmp>0)
    {
        x.m_right = insertRec(x.m_right, key, val);
    }
    else
    {
        x.m_value = val;
    }
    
    return x;     
}

打印根目录:

public void printRoot()
{
    System.out.println("the root is: " + m_root.m_key);
}

我的主要课程:

public static void main(String[] args)
{
   binaryTree bt = new binaryTree();
   bt.insert("a", "data a");
   bt.insert("b", "data b");
   bt.insert("c", "data c");
   bt.printRoot();
}

我从打印 root 得到“a”作为 root 结果,我尝试打印 root.m_left 它显示为空。有什么我可能错过的吗?

【问题讨论】:

    标签: java binary-search-tree dsa


    【解决方案1】:

    第一个if-statement 之后的递归部分将始终被执行。另外,鉴于它是 BST,如果 comp &lt;= 0 recur left:

    if(x == null) { 
      x = new TreeNode(key,val);
    } else {  
      int cmp = key.compareTo(x.m_key);
      if(cmp <= 0) {
        x.m_left = insertRec(x.m_left, key, val);
      } else {
        x.m_right = insertRec(x.m_right, key, val);
      }
    }
    return x;
    

    【讨论】:

    • 非常感谢您回复并指出比较部分,对不起,但我不太明白这里的 if 语句有什么区别,我试图替换我的代码进行测试但是输出是一样的。
    • “我试图打印 root.m_left 它显示为空。有什么我可能错过的吗?” - 你的根节点有键“a”,现在如果你用键“b”插入节点,它将作为右子节点插入。类似地,对于键为“c”的节点,它将作为节点 b 的右子节点插入。因此节点 a 不存在左子节点,这就是为什么您在打印 root.m_left 时看到 null
    • 哦!我现在明白了,这非常清楚和有帮助!谢谢!!
    猜你喜欢
    • 2021-09-01
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2015-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多