BST to Linked List

/****
17.13
the data structure BiNode could be used to represent both a binary tree (where node 1 is the left node
and node 2 is the right node) or a doubly linked list(where node1 is the previous node and node 2 is the next node)
Implement a method to convert a binary search tree(implemented with BiNode) into a doubly linked list. The value
should be kept in order and the operation should be performed in place

complexity O(N^2) N is the number of nodes
*****/

#include<iostream>

using namespace std;

struct BiNode
{
       BiNode *node1, *node2;
       int val;
};

BiNode * getleftTail(BiNode *left) {
       BiNode *tail;
       tail = left;
       while (tail->node2 != nullptr)
       {
              tail = tail->node2;
       }
       return tail;
}

BiNode* BST2List(BiNode *root) {
      
       BiNode *left, *right, *leftTail;
       //base case
       if (root->node1 == nullptr || root->node2 == nullptr) return root;

       left = BST2List(root->node1);
       right = BST2List(root->node2);

       leftTail = getleftTail(left);

       root->node1 = leftTail;
       leftTail->node2 = root;
       root->node2 = right;
       right->node1 = root;

       return left;
}



Comments

Popular posts from this blog

Sudoku

Longest prefix matching - trie

Climbing Stairs