簡體   English   中英

在二叉樹中插入節點-將迭代轉換為遞歸

[英]Insert a node in a binary tree - Convert iterative to recursive

重復問題:

最近,我正在閱讀數據結構(二叉搜索樹),我非常了解遞歸並且也可以對其進行跟蹤。

我使用了一種始終對我有用的方法,即編寫帶有循環的程序,然后消除循環並編寫遞歸函數,基本條件將與循環退出條件相同。

但是,如果要編寫一個沒有我的循環方法的代碼,就會失敗。 我無法編寫一個遞歸函數以在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;
}

編輯:對不起,您以前沒有發布代碼。 這是我編寫的用於插入節點的代碼,現在如何將其轉換為遞歸方法?

遞歸插入始終會問以下問題:是否可以在當前root插入節點? 如果不是因為root not 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM