forked from theutpal01/HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlevel_order_traversal.py
49 lines (34 loc) · 1.04 KB
/
level_order_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
48
49
from typing import List
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insertIntoBST(self, root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = self.insertIntoBST(root.left, val)
else:
root.right = self.insertIntoBST(root.right, val)
return root
def bfs(self, node, level, hashmap):
if not node:
return hashmap
if level not in hashmap:
hashmap[level] = [node.val]
else:
hashmap[level].append(node.val)
self.bfs(node.left, level + 1, hashmap)
self.bfs(node.right, level + 1, hashmap)
return hashmap
def levelOrder(self, root) -> List[List[int]]:
if not root:
return []
return list(self.bfs(root, 0, {}).values())
if __name__ == "__main__":
tree = TreeNode(10)
nums = [5, 11, 12, 34, 3, 1]
for num in nums:
tree.insertIntoBST(tree, num)
print(tree.levelOrder(tree))