forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvert Binary Tree.py
38 lines (27 loc) · 936 Bytes
/
Invert Binary Tree.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# 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 = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def dfs(root):
if not root:
return None
root.left,root.right = dfs(root.right), dfs(root.left)
return root
return dfs(root)
2nd Solution:
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
def helper(root):
if not root:
return None
left = helper(root.left)
right = helper(root.right)
root.left = right
root.right = left
return root
helper(root)
return root