牛客網——二叉木の鏡像(C++、python)
1162 ワード
タイトルの説明
指定したツリーを操作し、ソースツリーのミラーに変換します.
説明を入力:
C++
python
指定したツリーを操作し、ソースツリーのミラーに変換します.
説明を入力:
:
8
/ \
6 10
/ \ / \
5 7 9 11
8
/ \
10 6
/ \ / \
11 9 7 5
C++
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot)
{
if(pRoot)
{
TreeNode* p=pRoot->left;
TreeNode* q=pRoot->right;
pRoot->left=q;
pRoot->right=p;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
}
};
python
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
#
def Mirror(self, root):
# write code here
if root:
root.left,root.right=root.right,root.left
self.Mirror(root.left)
self.Mirror(root.right)