使用递归的二叉搜索树插入

Binary Search Tree Insertion using Recursion

我在以下代码的逻辑中做错了什么: return 只是插入节点的值,而不是整棵树。 (见输出)

使用根节点打印树节点的方法是predefined.I这里只需要return树的根

 /* Node is defined as :
 class Node 
 int data;
 Node left;
 Node right;

 */

static Node Insert(Node root,int value)
 {       
  if(root == null){
     root = new Node();
     root.data= value ;
     return root;   
  }

 else{
  if(value<root.data)
   return Insert(root.left,value);

 else if(value > root.data)
     return  Insert(root.right,value);

 else return null;    
    }

   }

输入 -

   5           //number of nodes

  4 2 3 1 7    // values of nodes

   6           //value of node to be inserted

(预期)输出:

1 2 3 4 6 7

我的输出:

 6

修改if条件为:

if(root == null)
{
 root = new Node();
 root.data= value ;
 root.left=null;
 root.right=null;
 return root;
}

并将else条件修改为:

else
{
  if(value<root.data)
   {
     root.left=Insert(root.left,value);
     return root;
   }
  else if(value > root.data)
   {
     root.right= Insert(root.right,value);
     return root;
   }
  else 
   {
     System.out.println("duplicate value"); 
     return root;
   }
}