-
Notifications
You must be signed in to change notification settings - Fork 0
/
binary_tree_level_order_traversal.py
60 lines (49 loc) · 1.35 KB
/
binary_tree_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
50
51
52
53
54
55
56
57
58
59
60
# Definition for a binary tree node.
from typing import Optional, List
from collections import deque
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if root is None:
return root
q = []
return_list = []
q.append(root)
while len(q) > 0:
level_data = []
l = len(q)
for i in range(l):
current_data = q.pop(0)
level_data.append(current_data.val)
if current_data.left is not None:
q.append(current_data.left)
if current_data.right is not None:
q.append(current_data.right)
return_list.append(level_data)
return return_list
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node4 = TreeNode(4)
node5 = TreeNode(5)
node6 = TreeNode(6)
node7 = TreeNode(7)
node8 = TreeNode(8)
node9 = TreeNode(9)
node10 = TreeNode(10)
node11 = TreeNode(11)
node1.left = node2
node1.right = node3
node2.left = node4
node2.right = node5
node3.left = node6
node3.right = node7
node4.left = node8
node4.right = node9
node6.left = node10
node7.right = node11
print(Solution().levelOrder(node1))