Convert a binary search tree to a sorted two-way linked list
Question: enter a binary search tree and convert it into a sorted two-way linked list. You cannot create any
The new node only adjusts the pointer direction.
For example, Binary Search Tree
10
/\
6 14
/\/\
4 8 12 16
Convert to a two-way linked list
4 = 6 = 8 = 10 = 12 = 14 = 16.
Idea: You can use recursive methods to deal with many questions about the tree. This question is no exception. We will consider this question from the basic idea.
A binary tree is programmed with a two-way linked list, which is eventually an ordered sequence, that is, the result of the Middle-order traversal. When we use the Middle-order traversal method to traverse a binary tree, we can traverse a node, yes, the right pointer of the forward node points to the current node, and the left pointer of the current node points to the forward node, and then points the forward node to the current node.
BinTree* head =NULL;void helper(BinTree* root,BinTree*& pre){if(root == NULL && root == NULL)return ;helper(root->left,pre);if(head == NULL)head = root;if(pre == NULL)pre = root;else{root->left = pre;pre->right = root;pre = root;}//cout<
value<<" "<
right,pre);}BinTree* SearchTreeConverstToList(BinTree* root){BinTree* pre = NULL;helper(root,pre);return head;}
Train of Thought 2: If we convert the right subtree into a two-way linked list for the current node, and then convert the left subtree into a two-way linked list, during the conversion, we marked the head node and tail node of the linked list. We only need to connect the current node to the tail of the Left subtree and the right subtree.
void helper_second(BinTree* root,BinTree*& head,BinTree*& tail){if(root==NULL || (root->left == NULL && root->right == NULL)){head = root;tail = root;return;}BinTree* left_head = NULL;BinTree* left_tail = NULL;BinTree* right_head = NULL;BinTree* right_tail = NULL;helper_second(root->left,left_head,left_tail);helper_second(root->right,right_head,right_tail);if(left_head == NULL)head = root;else{head = left_head;left_tail->right = root;root->right = left_tail;}if(right_head == NULL)tail = root;else{tail = right_tail;root->right = right_head;right_head->left = root;}}BinTree* ConverstToList(BinTree* root){BinTree* head=NULL;BinTree* tail = NULL;helper_second(root,head,tail);return head;}