本问题对应的 leetcode 原文链接:剑指 Offer 27. 二叉树的镜像
问题描述
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
解题思路
视频讲解直达: 本题视频讲解
代码实现
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null || (root.left == null && root.right == null)){
return root;
}
TreeNode left = mirrorTree(root.left);
TreeNode right = mirrorTree(root.right);
root.left = right;
root.right = left;
return root;
}
}
时间复杂度:O(n)
空间:树的高度。
Python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def mirrorTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root or (not root.left and not root.right):
return root
left = self.mirrorTree(root.left)
right = self.mirrorTree(root.right)
root.left = right
root.right = left
return root
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 || (!root->left && !root->right)) {
return root;
}
TreeNode* left = mirrorTree(root->left);
TreeNode* right = mirrorTree(root->right);
root->left = right;
root->right = left;
return root;
}
};
Go
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func mirrorTree(root *TreeNode) *TreeNode {
if root == nil || (root.Left == nil && root.Right == nil) {
return root
}
left := mirrorTree(root.Left)
right := mirrorTree(root.Right)
root.Left = right
root.Right = left
return root
}
JS
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var mirrorTree = function(root) {
if (root == null || (root.left == null && root.right == null)) {
return root;
}
let left = mirrorTree(root.left);
let right = mirrorTree(root.right);
root.left = right;
root.right = left;
return root;
};