Leikou's rewriting notes: Sword refers to Offer 27. Mirroring of the binary tree (traverse all the nodes of the tree using a temporary list, and exchange the left/right child nodes of each node.)

topic:

Sword refers to Offer 27, the mirror image of the binary tree

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

For example, enter:
Insert picture description here

Mirror output:
Insert picture description here

Example 1:

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

limit:

0 <= number of nodes <= 1000

Problem solution ideas:

Use the stack (or queue) to traverse all nodes of the tree, and exchange the left/right child nodes of each node.

Algorithm flow:
special case processing: when root is empty, directly return null;
initialization: stack (or queue), this article uses the stack, and joins the root node root.
Cyclic exchange: jump out when the stack is empty; pop
out: mark as node;
add child nodes: push the left and right child nodes of node into the stack;
exchange: exchange the left/right child nodes of node.
Return value: Return the root node root.

Complexity analysis:
time complexity O(N): where N is the number of nodes in the binary tree, and building a binary tree mirror requires traversing all nodes of the tree, which takes O(N) time.
Space complexity O(N): In the worst case (when the binary tree is full), the stack can store up to N/2 nodes at the same time, occupying O(N) additional space.

Problem solution python code:

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return
        s = [root]
        while s:
            node = s.pop()
            if node.left:
                s.append(node.left)
            if node.right:
                s.append(node.right)
            node.left, node.right = node.right, node.left
        return root

Insert picture description here

Author: jyd
link: https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/solution/mian-shi-ti-27-er-cha-shu-de-jing -xiang-di-gui-fu-/
Source: LeetCode https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof/

Guess you like

Origin blog.csdn.net/weixin_44414948/article/details/113783505
Recommended