【剑指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

代码

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 # 终止条件,父结点为空
        tmp = root.left # 暂存左儿子
        root.left = self.mirrorTree(root.right) # 递归右儿子,更改左儿子
        root.right = self.mirrorTree(tmp) # 递归左儿子,更改右儿子
        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==NULL) return NULL;
        TreeNode *L=mirrorTree(root->right);
        TreeNode *R=mirrorTree(root->left);
        root->left=L;
        root->right=R;
        return root;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章