【问题标题】:Binary Search Tree Insertion using Recursion使用递归的二叉搜索树插入
【发布时间】:2015-07-07 01:02:00
【问题描述】:

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

使用根节点打印树的节点的方法是预定义的,我这里只需要返回树的根即可。

 /* 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

【问题讨论】:

    标签: recursion tree binary-search-tree


    【解决方案1】:

    只要修改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;
       }
    }    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-15
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 2018-02-06
      • 2015-06-16
      相关资源
      最近更新 更多