java二叉搜索树插入递归似乎总是返回空根

问题描述

嗨,我目前正在尝试使用一些在线参考构建 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,val);
    }
    else if(cmp>0)
    {
        x.m_right = insertRec(x.m_right,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 它显示为空。有什么我可能错过的吗?

解决方法

第一个 if-statement 之后的递归部分将始终执行。此外,鉴于它是 BST,如果 comp <= 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,val);
  }
}
return x;

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...