算法提高之LeetCode刷题数据结构和算法分析

二叉树的镜像

2020-02-21  本文已影响0人  _阿南_

题目:

请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
     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
        

提交

Good

难得有一次好成绩啊!

// END 在家待的时间长了,脖子痛,My God

上一篇 下一篇

猜你喜欢

热点阅读