二叉树的镜像

来源:互联网 发布:linux中dns配置文件 编辑:程序博客网 时间:2024/06/05 12:16

题目描述:
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述
解法一:
递归

# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    def Mirror(self, root):        if root:            root.left,root.right = root.right, root.left            self.Mirror(root.left)            self.Mirror(root.right)        return root

解法二:
非递归,利用栈。

class Solution:    def Mirror(self, root):        if not root:            return root        stack = []        stack.append(root)        while stack:            node = stack.pop(-1)            if node.left or node.right:                node.left, node.right =node.right, node.left            if node.left:                stack.append(node.left)            if node.right:                stack.append(node.right)        return root
原创粉丝点击