-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeInorderTraversal_Day32.py
More file actions
54 lines (41 loc) · 1.19 KB
/
Copy pathBinaryTreeInorderTraversal_Day32.py
File metadata and controls
54 lines (41 loc) · 1.19 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
#Brute Force Approach
#Using a class-level/global list (not recommended)
class Solution:
def __init__(self):
self.result = []
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root:
self.inorderTraversal(root.left)
self.result.append(root.val)
self.inorderTraversal(root.right)
return self.result
# TC - O(N)
# SC - O(N)
#Better Approach
#Recursive and pure
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
def inorder(node):
if not node:
return []
return inorder(node.left) + [node.val] + inorder(node.right)
return inorder(root)
# TC - O(N)
# SC - O(N)
#Optimal Approach
#Iterative using Stack
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
stack = []
current = root
while current or stack:
while current:
stack.append(current)
current = current.left
current = stack.pop()
res.append(current.val)
current = current.right
return res
# TC - O(N)
# SC - O(N)