题目:
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
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:
children = list()
children.append(root)
while len(children) > 0:
children_temp = list()
for child in children:
if child is not None:
node = child.left
child.left = child.right
child.right = node
if child.left is not None:
children_temp.append(child.left)
if child.right is not None:
children_temp.append(child.right)
children = children_temp
return root
提交
![](https://img.haomeiwen.com/i1534405/9e92b4c583037d31.png)
难得有一次好成绩啊!
// END 在家待的时间长了,脖子痛,My God
网友评论