Topic
Complete a function, enter a binary tree, build its mirrored binary tree
Analysis
The most straightforward solution to this problem is recursion, exchanging left and right subtrees (i.e., exchanging children around).
Code
1 voidMirrortree (treenode*root)2 {3 if(!root)4 ThrowStd::exception ("Invalid input.");5 6 //swap The left and right subtree7treenode* tmp=root->Pleft;8Root->pleft=root->Pright;9root->pright=tmp;Ten One //recursion A if(root->pleft) -Mirrortree (root->pleft); - if(root->pright) theMirrortree (root->pright); - -}
can also be used in a non-recursive way to solve, for reference to the idea of layered traversal, with a two-way queue, layered traversal of the binary tree, in the process of the traversal of each node of the child can be exchanged
1 voidMirrorTree1 (treenode*root)2 {3 if(!root)4 ThrowStd::exception ("Invalid input.");5 6Deque<treenode*>dq;7treenode*node;8 Dq.push_back (root);9 while(Dq.size () >0)Ten { OneNode=Dq.front (); A - if(node->pleft==null&&node->pright==NULL) - { the Dq.pop_front (); - Continue; - } -treenode* tmp=node->Pleft; +Node->pleft=node->Pright; -node->pright=tmp; + A if(node->pleft) atDq.push_back (node->pleft); - if(node->pright) -Dq.push_back (node->pright); - Dq.pop_front (); - } -}
Image of algorithm Problem 22 tree