Given a binary tree and two levels (low and high), print all the nodes present in the binary tree between those levels inclusively. The levels are specified starting from level 0 (root level) to level n. Nodes at each level are printed in level order.
graph TD;
subgraph l0["Level 0"]
A("1")
end
subgraph l1["Level 1"]
B("2")
C("3")
end
subgraph l2["Level 2"]
D("4")
E("5")
F("6")
G("7")
end
A --- B & C
B --- D & E
C --- F & G
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Input:
Binary Tree:
1/ \
23/ \ / \
4567 low =1 high =2 Output:
234567 Explanation:
Nodes at level 1 are [2, 3]. Nodes at level 2 are [4, 5, 6, 7]. These nodes are between levels 1and2 inclusively.
Input:
Binary Tree:
1/2/ \
34/5 low =2 high =3 Output:
345 Explanation:
Nodes at level 2 are [3, 4]. Nodes at level 3 are [5]. These nodes are between levels 2and3 inclusively.
Tree Traversal: Use breadth-first search (BFS) for level-order traversal as it naturally processes nodes level by level.
Node Filtering: During traversal, keep track of the current level. If the current level falls between the provided low and high bounds, add the nodes of that level to the result.
Control Bounds: Stop processing nodes once the traversal reaches a level higher than high.