-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathBinary Tree Inorder Traversal.py
47 lines (36 loc) · 1.05 KB
/
Binary Tree Inorder Traversal.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
44
45
46
47
from typing import List, Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
inorder = []
stack = []
while stack or root is not None:
if root:
stack.append(root)
root = root.left
else:
node = stack.pop()
inorder.append(node.val)
root = node.right
return inorder
class Solution:
"""
Time: O(n)
Memory: O(n)
"""
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
return list(self.inorder_generator(root))
@classmethod
def inorder_generator(cls, tree: Optional[TreeNode]):
if tree is not None:
yield from cls.inorder_generator(tree.left)
yield tree.val
yield from cls.inorder_generator(tree.right)