1. Convert the binary search tree into a sorted two-way linked list

Source: Internet
Author: User


1. Convert the binary search tree into a sorted two-way linked list
Question:
Enter a binary search tree and convert it into a sorted two-way linked list.
You must not create any new node. You only need to adjust the pointer point.

10
/\
6 14
/\/\
4 8 12 16

Convert to a two-way linked list
4 = 6 = 8 = 10 = 12 = 14 = 16.

First, we define the data structure of the Binary Search Tree node as follows:
Struct bstreenode
{
Int m_nvalue; // value of Node
Bstreenode * m_pleft; // left child of Node
Bstreenode * m_pright; // right child of Node

};


Solution 1: Get the head of a tree, convert the left to a bidirectional list, then connect it to the head, convert the right to a bidirectional list, and then connect it to the right of the head. Recursion of this process.

Complexity: every node calls a function once, so the complexity is N.

#include "BSTreeNode.h"#include <cstddef>inline BSTreeNode* getListLeft(BSTreeNode* node){if(node == NULL) return NULL;while(node->m_pLeft != NULL){node = node->m_pLeft;}return node;}inline BSTreeNode* getListRight(BSTreeNode* node){if(node == NULL) return NULL;while(node->m_pRight != NULL){node = node->m_pRight;}return node;}BSTreeNode* tree2List_1(BSTreeNode *head){if(head->m_pLeft != NULL &&head->m_pLeft->m_pRight != head){BSTreeNode* node = tree2List_1(head->m_pLeft);BSTreeNode* right = getListRight(node);right->m_pRight = head;head->m_pLeft = right;}if(head->m_pRight != NULL && head->m_pRight->m_pLeft != head){BSTreeNode* node = tree2List_1(head->m_pRight);BSTreeNode* left = getListLeft(node);left->m_pLeft = head;head->m_pRight = left;}return head;}BSTreeNode* tree2List(BSTreeNode *head){return getListLeft(tree2List_1(head));}



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.