欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二叉树翻转镜像

程序员文章站 2022-06-01 08:42:31
...

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

二叉树翻转镜像

递归实现:

#include<iostream>
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<TreeNode*>  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();

    }
};