【劍指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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章