树练习(3)

class Solution(object):
    def mirrorTree(self, root):
        if not root:
            return None;
        if not root.left and not root.right:
            return root;
        root.left,root.right=root.right,root.left;
        if root.left:
            self.mirrorTree(root.left);
        if root.right:
            self.mirrorTree(root.right);
        return root;

利用Python自带的交换值方式:

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return None
        root.left,root.right = self.mirrorTree(root.right),self.mirrorTree(root.left)
        return root

使用非递归,栈的处理方式

# 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 None
        stack=[root]
        while stack:
            node=stack.pop()
            if node.left:stack.append(node.left)
            if node.right:stack.append(node.right)
            node.left,node.right = node.right,node.left
        return root
            
原文地址:https://www.cnblogs.com/topass123/p/12760624.html