Question: enter a binary search tree and convert the tree to its image. That is, in the converted Binary Search Tree, the left subtree has more nodes than the right subtree. Use recursive and cyclic methods to convert tree images.
For example, enter:
8
/\
6 10
/\/\
5 7 9 11
Output:
8
/\
10 6
/\/\
11 9 7 5
Method 1: recursion. For the root node T, exchange the Left and Right sons, and then perform the same operation on the left and right sons respectively.
Method 2: Non-recursion, which can be achieved through queues or stacks
# Include "stdafx. H "# include <iostream >#include <queue> using namespace STD; typedef struct node {int data; struct node * left; struct node * right;} node, * bitree; void insert (bitree & T, int ch) // create a binary sorting tree {If (t = NULL) {bitree t = (bitree) malloc (sizeof (node )); t-> DATA = CH; t-> left = NULL; t-> right = NULL; t = T;} else if (CH> T-> data) {insert (t-> right, CH);} else if (CH <t-> data) {insert (t-> left, CH );} else {cout <"dupli Cate value in Ordered Tree "<Endl ;}} void travel (bitree t) {If (T! = NULL) {travel (t-> left); cout <t-> data <""; // traverse travel (t-> right) in the middle order );}} void getmirrorrecur (bitree t) // recursive swap subtree {If (t = NULL) return; bitree TMP = T-> left; t-> left = T-> right; t-> right = TMP; get1_recur (t-> left); get1_recur (t-> right);} void get1_recurbyqueue (bitree T) // use the queue to exchange left and right subtree {If (t = NULL) return; queue <bitree> qu; qu. push (t); // join the while (! Qu. empty () {bitree root = Qu. front (); qu. pop (); bitree TMP = root-> left; root-> left = root-> right; root-> right = TMP; If (root-> left) Qu. push (root-> left); If (root-> right) Qu. push (root-> right) ;}} int main () {bitree root = NULL; int ch; CIN> CH; while (Ch! = 0) // create a tree {insert (root, CH); CIN> CH;} travel (Root); cout <Endl; // get1_recur (Root ); // recursive exchange subtree getcurbyqueue (Root); travel (Root); getchar (); Return 0 ;}