微信公众号:路人zhang
扫码关注微信公众号

回复“面试手册”,获取本站PDF版

回复“简历”,获取高质量简历模板

回复“加群”,加入程序员交流群

回复“电子书”,获取程序员类电子书

当前位置: 算法 > 剑指offer > 剑指offer 27.二叉树的镜像

题目描述

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

例如输入:

     4  
   /   \  
  2     7  
 / \   / \  
1   3 6   9

镜像输出:

     4  
   /   \  
  7     2  
 / \   / \  
9   6 3   1

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

限制:

0 <= 节点个数 <= 1000


题解

(BFS,前序遍历) O(n)

翻转二叉树就是翻转二叉树的每个节点的左右孩子,把握住这一点,首先我们需要遍历二叉树,遍历二叉树的方法有很多,比如:前序遍历、后序遍历、层序遍历,但只有中序遍历不可以。

为什么中序边里不可以? 中序遍历会导致某些节点的左右孩子被翻转两次,而某些节点却一次都没有翻转,这是和中序遍历的过程有关系的,当我们遍历的当前节点是根节点的时候,首先翻转根节点的左右孩子,下一步要将根节点的右孩子的左边一条链都加入到栈中,而此时的右孩子恰恰是原树的左孩子,所以原树的左子树又会被翻转一次,而原树的右孩子却一次都没有被翻转,因此不能用中序遍历来翻转二叉树。

时间复杂度

O(n)

空间复杂度

O(logn),最坏情况下二叉树呈链状,空间复杂度为 O(n)。

C++代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if (!root) return nullptr;
        mirrorTree(root->left);
        mirrorTree(root->right);
        swap(root->left, root->right);
        return root;
    }
};

Java 代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        mirrorTree(root.left);
        mirrorTree(root.right);
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }
}

Python 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        self.mirrorTree(root.left)
        self.mirrorTree(root.right)
        root.left, root.right = root.right, root.left
        return root

本文由读者提供Github地址:https://github.com/tonngw


点击面试手册,获取本站面试手册PDF完整版