Binary tree Image (c + + version) __c++

Source: Internet
Author: User

Topic:

Given the source binary tree, the design algorithm realizes its mirror image.


Ideas:

For the problem of binary tree, it is necessary to consider the non recursive implementation of the recursive method.

This is a good recursive implementation, for the first node traversal, each exchange its left and right subtree. Then recursively calls to its subtree.


For non-recursive implementations, you need to use a secondary stack to hold the header nodes. (Sequence traversal)


Note:

The binary tree node is defined as follows:

typedef int DATATYPE;

struct Node

{

DataType Val;

struct Node *left;

struct Node *right;

Node (DataType _val):

Val (_val), left (null), right (null) {}

};

Paste Code:

void Mirror (TreeNode *proot) {if (0) {//recursive implementation if (Proot = = NULL) {
            Return
            } TreeNode *temp;
            temp = proot->left;
            Proot->left = proot->right;

            Proot->right = temp;
            Mirror (Proot->left);
        Mirror (Proot->right);
            
            else {//non-recursive implementation (requires the use of a secondary stack) stack<treenode*> Stk;
            if (Proot = = NULL) {return;
            
            } stk.push (Proot); If the stack is not empty the description also needs to traverse the while (!stk.empty ()) {//Get the current traversal subtree header node TreeNode *
                Head = Stk.top ();
                
                Stk.pop ();
                    Any subtree of the head node is not empty and needs to be exchanged if (Head->left | | head->right) {TreeNode *temp;
        temp = head->left;            Head->left = head->right;
                Head->right = temp; //Press into the new head node if (head->left) {Stk.push (head-&gt
                ; left);
                } if (head->right) {Stk.push (head->right);
    }} return; }

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.