-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path102. Binary Tree Level Order Traversal (BFS) 20.3.15 Medium
More file actions
88 lines (83 loc) · 3.04 KB
/
102. Binary Tree Level Order Traversal (BFS) 20.3.15 Medium
File metadata and controls
88 lines (83 loc) · 3.04 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Solution:-------------------------------------------------- Queue & BFS ----- https://www.youtube.com/watch?v=B0n3gqPKKic
------------------------- Time complexity : O(n). Because we traverse the entire input tree once, the total run time is O(n),
------------------------- where n is the total number of nodes in the tree.
------------------------- Space complexity : O(n)
------------------------- BFS will have to store at least an entire level of the tree in the queue (sample queue implementation).
------------------------- With a perfect fully balanced binary tree, this would be (n/2 + 1) nodes (the very last level)
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrder(self, root):
if root is None:
return None
queue, res = [root], []
while queue:
currlist = []
for i in range(len(queue)):
pop_element = queue.pop(0) # queue -> pop(0) not pop()!! First in First out!!
if pop_element.left:
queue.append(pop_element.left)
if pop_element.right:
queue.append(pop_element.right)
currlist.append(pop_element.val)
res.append(currlist[:])
return res # Do not forget to initilize res in the beginning!
# res = []
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
Java Version:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (q.size() != 0) {
List<Integer> curr = new ArrayList<>();
int currIterTime = q.size();
for (int i = 0; i < currIterTime; i ++) {
TreeNode popNode = q.poll();
curr.add(popNode.val);
if (popNode.left != null) {
q.offer(popNode.left);
}
if (popNode.right != null) {
q.offer(popNode.right);
}
}
res.add(curr);
}
return res;
}
}