使用递归

时间:2015-07-07 01:02:00

标签: recursion tree binary-search-tree

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

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

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

1 个答案:

答案 0 :(得分:1)

只需将条件修改为:

viewControllers

并将else条件修改为:

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