Posted on 2023-02-18 16:53
Uriel 阅读(32)
评论(0) 编辑 收藏 引用 所属分类:
搜索 、
数据结构 、
闲来无事重切Leet Code
翻转二叉树,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)