How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space

前端 未结 11 1104
借酒劲吻你
借酒劲吻你 2021-01-31 22:12

How to convert a binary tree to binary search tree in-place, i.e., we cannot use any extra space.

11条回答
  •  再見小時候
    2021-01-31 22:25

    Do the PostOrder Traversal and from that create a Binary search tree.

    struct Node * newroot = '\0';
    
    struct Node* PostOrder(Struct Node* root)
    {
          if(root != '\0')
          {
              PostOrder(root->left);
              PostOrder(root->right);
              insertBST(root, &newroot);
          }
    }
    
    insertBST(struct Node* node, struct Node** root)
    {
       struct Node * temp, *temp1;
       if( root == '\0')
       {
          *root == node;
           node->left ==  '\0';
           node->right == '\0';
       }
       else
       {
           temp = *root;
           while( temp != '\0')
           {
               temp1= temp;
               if( temp->data > node->data)
                   temp = temp->left;
               else
                   temp = temp->right;
           }
           if(temp1->data > node->data)
           {
               temp1->left = node;
           }
           else
           {
               temp1->right = node;
           }
           node->left = node->right = '\0';
        }
    }
    

提交回复
热议问题