Title: Enter a two-dollar lookup tree to convert the tree to its image, that is, in the converted two-dollar lookup tree, the Zuozi node is greater than
The nodes of the right sub-tree. Recursive and cyclic methods are used to complete the image transformation of the tree.
For example, enter:
8
/ \
6 10
/\ /\
5 7 9 11
Output:
8
/ \
10 6
/\ /\
11 9 7 5
Idea: This is also a recursive topic, for the current node, if it is not a null node or leaf node, then only need to exchange the left and right child nodes. This recursively calls the left and right subtrees again.
void Convertmirror (bintree* root) {if (root = NULL | | (Root->left = = NULL &&root->right = = NULL)) return; bintree* temp = Null;temp = Root->left;root->left = Root->right;root->right = Temp;if (root->left! = NULL) C Onvertmirror (Root->left); if (root->right! = NULL) convertmirror (root->right);}
Of course, you can not use recursion, use the stack space to assist, remove the node from the top of the stack, exchange the left and right nodes, if the left and right nodes are not empty, press into the stack
void Convertmirrornoiter (bintree* root) {stack<bintree*> st;if (root = NULL) return; St.push (root); bintree* Temp;while (!st.empty ()) {temp = St.top (); St.pop (); bintree* cur = temp->left;temp->left = Temp->right;temp->right = Cur;if (temp->left! = NULL) St.push (temp- >left); if (temp->right! = NULL) St.push (temp->right);}}
Image of Binary search tree