226. Reverse Binary Tree

Question :
Give you the root node root of a binary tree, flip the binary tree, and return its root node.
insert image description here
insert image description here

Idea:
Because I just finished the symmetric binary tree, I first thought to exchange the left child of the left node with the right child of the right node, and the right child of the left node with the left child of the right node, but it may be programming An error was reported for an unfamiliar reason. Later, I looked at the answer and found that the same is true. Finally, I found a more concise code. The idea is to first swap the left and right nodes of the left subtree, then the left and right nodes of the right node, and finally the left and right subtrees. The trees are swapped, and finally the root node is returned. But later found out that the left and right nodes are exchanged first and then the left and right node exchange of the left subtree is the same as the left and right exchange of the right node (execute the 16th line of code first and execute the same later).
The specific code is as follows: (note that a null value is returned when the root node is empty)

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def invertTree(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        if root == None:
        	return None
        # 左右结点交换
        root.left, root.right = root.right, root,left
        #左子树左右结点交换
        self.invertTree(root.left)
        # 右子树左右结点交换
        self.invertTree(root.right)
        return root

The final result is the code submission:
insert image description here
reference link

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324340560&siteId=291194637