Title: Enter a two-dollar lookup tree to convert the two-dollar lookup tree into a sorted doubly linked list. Requires that you cannot create any
A new node that only adjusts the pointer's point.
For example, the two-dollar lookup tree
10
/ \
6 14
/ \ / \
4 8 12 16
Convert to doubly linked list
4=6=8=10=12=14=16.
Idea: A recursive approach can be used to deal with many of the tree's problems. This problem is no exception. We consider this subject from the most basic ideas.
A binary tree programming a doubly linked list, eventually an ordered sequence, that is, the result after the middle sequence traversal, then when we traverse the binary tree in the way of the middle order traversal, we traverse to a node, the right pointer of the pre-order node points to the current node, and then the left pointer of the current node points to the pre-order node. The pre-order node is then directed to the current node.
bintree* Head =null;void Helper (bintree* root,bintree*& Pre) {if (root = = NULL && root = = null) return; Helper (ro OT->LEFT,PRE); if (head = = null) head = root;if (pre = = null) Pre = Root;else{root->left = Pre;pre->right = Root;pre = Root;} cout<<root->value<< " " <<endl;helper (Root->right,pre); Bintree* searchtreeconversttolist (bintree* root) {bintree* pre = Null;helper (Root,pre); return head;}
Second: If for the current node, we convert the right subtree into a doubly linked list, and then convert the left subtree into a doubly linked list, when we are all marked the head node and tail node of the list, then we just need to connect the current node and the left sub-tree's tail, and the right subtree of the head connected.
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;}
Binary lookup tree converted to a sorted doubly linked list