leetcode with python:226. Invert Binary Tree

题目:

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%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章