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));}