美文网首页
二叉树的镜像

二叉树的镜像

作者: su945 | 来源:发表于2020-05-06 23:25 被阅读0次

    题目描述

    操作给定的二叉树,将其变换为源二叉树的镜像。

    二叉树的镜像定义:源二叉树
    8
    / \
    6 10
    / \ / \
    5 7 9 11
    镜像二叉树
    8
    / \
    10 6
    / \ / \
    11 9 7 5

    问题分析

    BFS和DFS的套路,要么递归实现要么利用队列进行层序遍历。

    解题思路1

    • 递归法
    /*
    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){
                swap(pRoot->left, pRoot->right);
                Mirror(pRoot->left);
                Mirror(pRoot->right);
            }
        }
    };
    

    解题思路2

    • 层序遍历
    /*
    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)
            {
                return;
            }
            //队列特点是先进先出
            queue<TreeNode*> que;
            que.push(pRoot);
            TreeNode* tmp = NULL;
            while(!que.empty())
            {
                //取出队头元素,并弹出
                tmp = que.front();
                que.pop();
                swap(tmp->left,tmp->right);
                if(tmp->left)
                {
                    que.push(tmp->left);
                }
                if(tmp->right)
                {
                    que.push(tmp->right);
                }
            }
    
        }
    };
    

    相关文章

      网友评论

          本文标题:二叉树的镜像

          本文链接:https://www.haomeiwen.com/subject/ibknghtx.html