题目
输入一个二叉树,将它变换为它的镜像。
数据范围
树中节点数量 [0,100][0,100]。
样例
输入树:
8
/ \
6 10
/ \ / \
5 7 9 11
[8,6,10,5,7,9,11,null,null,null,null,null,null,null,null]
输出树:
8
/ \
10 6
/ \ / \
11 9 7 5
[8,10,6,11,9,7,5,null,null,null,null,null,null,null,null]
解析
先交换左右子树,然后如此递归操作左右子树
代码
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:
void mirror(TreeNode* root) {
if (!root) return;
swap(root->left, root->right);
mirror(root->left);
mirror(root->right);
}
};
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 mirror(self, root):
"""
:type root: TreeNode
:rtype: void
"""
if root is None:
return
root.left, root.right = root.right, root.left
self.mirror(root.left)
self.mirror(root.right)
GO
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func mirror(root *TreeNode) {
if root == nil {
return
}
root.Left, root.Right = root.Right, root.Left
mirror(root.Left)
mirror(root.Right)
}