二叉树翻转镜像

题目地址:https://www.nowcoder.com/practice/564f4c26aa584921bc75623e48ca3011?tpId=13&tqId=11171&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

二叉树翻转镜像_第1张图片

递归实现:

#include
using namespace std;

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot==NULL)
        {
            return;
        }
     swap(pRoot->left,pRoot->right);
     Mirror(pRoot->right);
     Mirror(pRoot->left);
    }
};

非递归实现:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    void Mirror(TreeNode *pRoot) {
        if(pRoot==NULL)
        {
            return;
        }
        queue  q;
        q.push(pRoot);
        while(!q.empty())
        {
            TreeNode *per = q.front();
            TreeNode *tmp = per->left;
            per->left = per->right;
            per->right = tmp;
            if(per->right!=NULL)
            {
                q.push(per->right);
            }
            if(per->left!=NULL)
            {
                q.push(per->left);
            }
        }
        q.pop();

    }
};

你可能感兴趣的:(C++)