Enter a binary search tree and now convert the two-fork search tree into a sorted doubly linked list.

Source: Internet
Author: User

First, the problem description

Enter a binary search tree and now convert the two-fork search tree into a sorted doubly linked list. And in the process of conversion, you cannot create any new nodes, only the point of the node pointer in the tree can be adjusted to implement.

Second, the realization of ideas

In the binary search tree, each node has two pointers to its left and right subtrees, and the value of the left subtree node is always less than the parent node value, and the value of the right subtree node is always greater than the parent node value. In a doubly linked list, each node also has two pointers, which point to the previous node and the latter node, respectively. So the nodes of the two data structures are consistent, the binary search tree is a two-fork search tree, doubly linked list is a doubly linked list, just because two pointers point to a different

idea: when converting to a sort doubly linked list, the pointer to the left Dial hand node is adjusted to the pointer to the previous node in the list, and the pointer to the right child node is adjusted to the pointer to the next node in the list. The operation of a tree, usually in the process of traversing the nodes of the tree, is done by implementing certain operations on the nodes, and this algorithm is no exception. Since the conversion of the two-way linked list is also ordered, and we can see from the above, when we traverse the binary search tree in the middle sequence, its traversal of the node is ordered, so the use of the traversal order here should be the middle order.

Recursive #include<iostream> #include <stack>using namespace std;struct binarytreenode{int  data; binarytreenode* left; binarytreenode* right; Binarytreenode (int x):d ata (x),  left (null),  right (null) {}};class binarytree{protected: binarytreenode* _root; Binarytreenode* _createbinarytree (int* arr, int& index, int size) { binarytreenode* root = null;if  (index < size&&arr[index] !=   ' # ') {Root = new binarytreenode (Arr[index]); Root->left = _createbinarytree ( arr, ++index, size); Root->right = _createbinarytree (arr, ++index, size);} Return root;} Void _clear (Binarytreenode* root) {if  (root == null) return;_clear (root->left); _ Clear (root->right);d elete root;} Void _convert (Binarytreenode* root, binarytreenode** head)//may change head, add reference to {if  (root& nbsp; == null) return; binarytreenode* cur = root;if  (Cur->left) _convert (root->left, head);cur-> left = *head;if  (*head) (*head)->right = cur;*head = cur;if  (cur- >right) _convert (cur->right, head);} Print and destroy the doubly linked list private:static void printlist (binarytreenode* head) {if  (head == null) Return binarytreenode* cur = head;while  (cur) {cout << cur->data <<   " ";if  (cur->left) cout <<  "prev"  << cur->left->data  <<  " ";if  (cur->right) cout <<  "Next"  << cur-> Right->data << endl;cur = cur->right;}} Static void destroy (Binarytreenode** head) {binarytreenode* cur = *head; binarytreenode* del = null;while  (cur) {del = cur;cur = cur->Right;delete del;} Head = null;} Public:binarytree (): _root (NULL) {}~binarytree () {_clear (_root);} BinaryTree (int *arr, int size) {Int index = 0;_root = _createbinarytree (arr, index, size);} Void preorder_non () {if  (_root == null) return; Binarytreenode* cur = _root;stack<binarytreenode*> s;s.push (_root);while  (! S.empty ()) {cur = s.top ();p rintf ("%d ",  cur->data); S.pop ();if  (cur->right) S.push (cur->right);if  (cur->left) s.push (Cur->left);}} Binarytreenode* transformlist () {if  (_root == null) return null;//return anonymous object// Should be sequentially traversed in order Binarytreenode* ret = null;_convert (_root, &ret);while  (ret !=  Null&&ret->left != null) ret = ret->left;_root = null; Printlist (ret);D Estroy (&ret);}; Void test1 () {int arr[] = { 10, 6, 4,  ' # ',  ' # ', 8,  ' # ',  ' # ', 14, 12,  ' # ',  ' # ', 16 }; BINARYTREE&NBSP;BT1 (arr, sizeof (arr)  / sizeof (arr[0]); bt1. Preorder_non (); Binarytreenode* head = bt1. Transformlist ();} Non-recursive  treenode * transfer (treenode * root) {    // left  will be used as previous pointer  (Point to a little one);     // right will be used as post pointer  (Point  to a large one);    if  (!root)  return NULL;     stack *s = new stack ();     treenode *curr,  *head, *tail;    curr = root;    head =  null, tail=null;    while (True)  {      &nbsP; while (Curr)          {             s->push (Curr);             curr = curr->left;        }                 if (S->isEmpty ())   Break;        curr = s->pop ();         //visit (curr)         //Add Curr node to the end of the doubly linked list          if  ( head==null)           { //curr is the first node in a linked list.             head = curr;             tail = curr;        }         else         {             tail->right = curr;            curr- >left = tail;            tail =  curr;  //Note that the value of the Tail->right pointer cannot be modified here, so far,                           // The right subtree of the current node has not yet been accessed.                  }                 while (!curr-> right)          {             if (S->isempty ())  break;             curr = s->pop ();             // Visit (Curr);            //             if  ( head==null)               {                 head = curr;                 tail = curr;             }            else              {                 tail->right = curr;                 curr->left = tail;                 tail = curr;              }         }        if  (curr->right)               curr = curr->right;         else break;    }    head->left =  NULL;    tail->right = NULL;    delete s;     return head;}


We have a variable head that records the converted list of end nodes, because in practice we return the pointer to the 1th node of the list (counting from 1), and the head points to the last node, and we can use that pointer to get the first node pointer from the end of the tail. But I'm not doing this here because it needs to traverse each node once and the time complexity is O (n). Instead, a pointer to the leftmost node of the two-fork sort tree is found before the transformation. Because the sort binary tree is ordered, the leftmost node is the smallest node, and our algorithm does not delete or add nodes, that is, the address of the node is not changed, so the leftmost node is the 1th node of the converted list, its time complexity is O (logn).

The algorithm starts from the root point to the left, finds the leftmost node, has a time complexity of O (Logn), and then iterates through each node in the two-fork sort tree for pointer transformation, whose time complexity is O (n), so the total time complexity is O (n).

As for the spatial complexity, because the Convertnode function makes recursive calls, its function has two open parameters, and the function call layer in the function stack does not exceed the height of the tree, so its space complexity is O (logn).



This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1835451

Enter a binary search tree and now convert the two-fork search tree into a sorted doubly linked list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.