题目:
Given the root of a binary tree, invert the tree, and return its root.
给定一棵二元树,将其左右反转后回传
透过简单的递迴,这题不算太难
# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclass Solution: def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: #防止root即为None return None temp=root.right root.right=root.left root.left=temp root.right=self.invertTree(root.right) root.left=self.invertTree(root.left) return root
将root的左右枝互换
接着再透过递迴向下,将root的左右枝之左右枝互换
直到碰到None为止
工程全部结束后,我们便得到一棵反转完的binary tree了
最后执行时间30ms(faster than 95.51%)
那我们下题见