-
Notifications
You must be signed in to change notification settings - Fork 0
/
python94.py
43 lines (34 loc) · 1.14 KB
/
python94.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
39
40
41
42
43
# 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 inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
# return self.dfs_recursive(root, res)
return self.dfs_iterative(root, res)
###### Iterative - Inorder
def dfs_iterative(self, node, res):
stack = []
# check if node -> left exists
while True:
if node:
stack.append(node)
node = node.left
else:
if len(stack) != 0:
node = stack.pop()
res.append(node.val)
node = node.right
else:
break
return res
###### Recursive - Inorder
def dfs_recursive(self, node, res):
if node:
self.dfs_recursive(node.left, res)
res.append(node.val)
self.dfs_recursive(node.right, res)
return res