关于二进制搜索树的问题--在二进制搜索树中插入数值。

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

我有一个关于我的作业的问题,我需要插入值到树上,但不是正确插入。

这是我的问题。 完成下面的方法 将一个包含值数据的新节点插入到由参数treePtr指向的二进制搜索树上 它应该插入数据,这样得到的树仍然是一棵二进制搜索树,并返回一个指向根节点的指针。注意,树一开始可能是空的(也就是说,参数 treePtr 的值可能是空的)。

这是我的代码。

public static TreeNode insertValue(TreeNode treePtr, int data) {

if (treePtr == null) {
            return new TreeNode(data, null, null);
        }

        if (treePtr != null) {
           new TreeNode(treePtr.data, null, null);
        }

        if (treePtr.data> data) {
            return insertValue(new TreeNode(data, null,treePtr ), data);
        }
        if (treePtr.data < data) {
                      return insertValue(new TreeNode(data, treePtr ,null), data);

}
        return treePtr;

这是我得到的答案

The tree for example:
   (- 632 (- 725 -))
After inserting 725, the tree should be:
   (- 632 (- 725 -))
Your solution produced this:
   ((- 632 -) 725 -)

我需要帮助解决这个问题

谢谢大家。

java tree binary-tree binary-search-tree
2个回答
© www.soinside.com 2019 - 2024. All rights reserved.