Image of algorithm Problem 22 tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.