题目来自LeetCode,链接:面试题27. 二叉树的镜像。具体描述为:请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
4
/ \
2 7
/ \ / \
1 3 6 9
镜像输出:
4
/ \
7 2
/ \ / \
9 6 3 1
一看到二叉树的题目,条件反射般就应该想到用递归来解决。像这道题的镜像,对于一个节点,我们先完成左子树和右子树的镜像(这里就是用递归来做),然后再对当前节点做镜像,也就是把当前节点的左右子节点互换,就可以完成镜像功能。明显时间复杂度为 O ( n ) O(n) O(n),空间复杂度为 O ( n ) O(n) O(n)(最坏的情况下即在二叉树退化为单链表的情况下,递归栈所需的空间)。
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 root;
}
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
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 root is None:
return root
root.left, root.right = self.mirrorTree(root.right), self.mirrorTree(root.left)
return root
提交结果如下: