-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0114-flatten-binary-tree-to-linked-list.py
More file actions
54 lines (45 loc) · 1.37 KB
/
0114-flatten-binary-tree-to-linked-list.py
File metadata and controls
54 lines (45 loc) · 1.37 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# time complexity: O(n)
# space complexity: O(1)
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def flatten(self, root: Optional[TreeNode]) -> None:
if root is None:
return None
if root.left is None and root.right is None:
return root
leftTail = self.flatten(root.left)
rightRail = self.flatten(root.right)
if leftTail:
leftTail.right = root.right
root.right = root.left
root.left = None
return rightRail if rightRail else leftTail
# time complexity: O(n)
# space complexity: O(1)
class Solution:
def flatten(self, root: TreeNode) -> TreeNode:
if not root:
return
current = root
while current:
if current.left:
last = current.left
while last.right:
last = last.right
last.right = current.right
current.right = current.left
current.left = None
current = current.right
return root
root = TreeNode(1)
root.left = TreeNode(2)
root.left.left = TreeNode(3)
root.left.right = TreeNode(4)
root.right = TreeNode(5)
root.right.right = TreeNode(6)
print(Solution().flatten(root))