二叉树的镜像

  1. 题目描述
    1. 思路分析

题目描述

操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树

            8
           /  \
          6   10
         / \  / \
        5  7 9 11
        镜像二叉树
            8
           /  \
          10   6
         / \  / \
        11 9 7  5

思路分析

  • 前序遍历
  • 判断左右子树交换
/*
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 == nullptr) {
            return;
        }
        // 交换左右子树
        TreeNode* temp = pRoot->left;
        pRoot->left = pRoot->right;
        pRoot->right = temp;
        // 递归左右子树
        Mirror(pRoot->left);
        Mirror(pRoot->right);
    }
};

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1056615746@qq.com

💰

Title:二叉树的镜像

Count:150

Author:攀登

Created At:2019-12-26, 23:12:31

Updated At:2024-06-15, 15:53:35

Url:http://jiafeimao-gjf.github.io/2019/12/26/sword-%E4%BA%8C%E5%8F%89%E6%A0%91%E9%95%9C%E5%83%8F/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.

×

Help us with donation