首页 > 解决方案 > 关于二叉搜索树的问题-向二叉搜索树插入值

问题描述

我对我的作业有疑问,我需要向树中插入值,但没有正确插入。

这是我的问题:完成以下方法,该方法将包含值数据的新节点插入到参数 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 -)

我需要这个问题的帮助。

谢谢大家。

标签: javatreebinary-treebinary-search-tree

解决方案


推荐阅读