在二叉树中插入节点 - 将迭代转换为递归

时间:2017-08-11 09:55:49

标签: c algorithm recursion binary-search-tree

重复问题:

最近,我正在阅读数据结构(二进制搜索树),我非常了解递归,并且可以跟踪它。

我使用的方法总是对我有用,即用循环编写程序,然后消除循环并编写递归函数,基本条件与循环退出条件相同。

但是当谈到没有我的循环方法编写一个时,我就失败了。 我无法编写递归函数来在二进制搜索树中插入节点。(虽然我通过参考解决方案正确理解了它。)

请指导我,如何改进?

#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node *left;//To store the address of the left child
    struct node *right;//To store the address of the Right child
};
struct node * root;
struct node *createnewnode(int x)
{
    struct node *n=(struct node *)malloc(sizeof(struct node));
    n->data=x;
    n->left=NULL;
    n->right=NULL;
    return n;
}
void Insert(int x)
{
    struct node *a,*b;
    struct node *temp=root;
    if(root==NULL)
        root=createnewnode(x);
    else
    {
        while(1)
         {
            if(x<=temp->data)
              {
                 if(temp->left!=NULL)
                    temp=temp->left;
                 else
                 {
                   a=createnewnode(x);
                   temp->left=a;
                   break;   
                 }
              }
            else
              {
                if(temp->right!=NULL)
                    temp=temp->right;
                 else
                 {
                   a=createnewnode(x);
                   temp->right=a;
                   break;   
                 }
              }  
         }
    }

}
int main()
{
    root==NULL;//Empty Tree
    Insert(15);
    Insert(10);
    Insert(20);
    Insert(25);
    return 0;
}

编辑:很抱歉以前没有发布代码。 这是我为插入节点编写的代码,现在如何将其转换为递归方法?

1 个答案:

答案 0 :(得分:0)

递归插入始终会询问以下问题:我可以在当前root中插入节点吗?如果不是因为rootnot null,那么我必须检查是否必须递归左侧或右侧子树并递归调用Insert

以下内容应足以让您了解如何操作

Node* Insert(Node* root, int x) {
  if (root == NULL)
    return createnewnode(x);
  else 
    if (x <= root->data) 
      root->left=Insert(root->left);
    else
      root->right=Insert(root->right);
}