Problem description:
Enter a binary search tree and convert it to its image,
That is, in the converted Binary Search Tree, the left subtree has more nodes than the right subtree.
Algorithm:
Test cases:
10
/\
5 11
/\
3 7
/\/\
2 4 6 9
//
1 8
Algorithm:
There are two ideas:
① Recursion. To flip a tree, you only need to flip the Left and Right sub-trees, and then switch the Left and Right sub-trees.
② Non-recursion. Set a queue and start processing from the root node: A person node is first added to the column. When the queue is not empty, the following processing is performed cyclically: retrieve a node from the queue, swap the left and right subtree positions and column its left and right subnodes (if any ). If the queue is empty, return.
Code implementation:
① Recursion
// Recursive template <class T> void reversetree (binarytreenode <t> * t) {<span style = "white-space: pre"> </span> If (! T) <span style = "white-space: pre"> </span> return; <span style = "white-space: pre "> </span> binarytreenode <t> * temp = new binarytreenode <t>; <span style =" white-space: pre "> </span> temp = T-> leftchild; <span style =" white-space: pre "> </span> T-> leftchild = T-> rightchild; <span style = "white-space: pre"> </span> T-> rightchild = temp; <span style = "white-space: pre "> </span> reversetree (t-> leftchild); <span style =" white-space: pre "> </span> reversetree (t-> rightchild ); <span style = "white-space: pre"> </span> return ;}
Non-recursion:
// Non-recursive template <class T> void reversetree2 (binarytreenode <t> * t) {If (! T) return; queue <binarytreenode <t> *> q; q. Add (t); binarytreenode <t> * TT = new binarytreenode <t>; while (! Q. isempty () {q. delete (TT); binarytreenode <t> * temp = new binarytreenode <t>; temp = tt-> leftchild; TT-> leftchild = tt-> rightchild; TT-> rightchild = temp; If (TT-> leftchild) Q. add (TT-> leftchild); If (TT-> rightchild) Q. add (TT-> rightchild );}}
Output test:
InOrder(n10);cout << endl;ReverseTree(n10);InOrder(n10);cout << endl;ReverseTree2(n10);InOrder(n10);cout << endl;
Output result:
Two ways to flip a binary search tree (image)