[Search and backtracking] Jianzhi Offer 27. Mirror image of binary tree

Title description : Please complete a function, input a binary tree, and the function outputs its mirror image.

Example : Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

Solution 1 : According to the definition of binary tree mirroring is to exchange the left subtree and right subtree, use DFS to traverse (preorder traversal) the binary tree, and exchange the left/right child nodes of each node to generate the mirror image of the binary tree.

# 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
        tmp = root.left
        root.left = self.mirrorTree(root.right)
        root.right = self.mirrorTree(tmp)
        return root

Solution 2 :
Use the auxiliary stack (or queue) to traverse all nodes of the tree according to the order of the hierarchy, and exchange the left/right child nodes of each node.

# 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

Guess you like

Origin blog.csdn.net/Rolandxxx/article/details/128997337