Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
翻转二叉树,DFS的过程中建reverse树


 1 #226
 2 #Runtime: 24 ms (Beats 26.41%)
 3 #Memory: 13.6 MB (Beats 27.71%)
 4 
 5 # Definition for a binary tree node.
 6 # class TreeNode(object):
 7 #     def __init__(self, val=0, left=None, right=None):
 8 #         self.val = val
 9 #         self.left = left
10 #         self.right = right
11 class Solution(object):
12     def invertTree(self, root):
13         """
14         :type root: TreeNode
15         :rtype: TreeNode
16         """
17 
18         if not root:
19             return root
20             
21         root_inv = TreeNode(root.val, root.right, root.left)
22 
23         def DFS(node):
24             if not node:
25                 return None
26             node_inv = TreeNode(node.val)
27             node_inv.left = DFS(node.right)
28             node_inv.right = DFS(node.left)
29             return node_inv
30 
31         return DFS(root)

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理