10. Nodes at Given Distance in Binary Tree
Problem Statement
My Approach
Let's take an example tree:
17
/ \
20 15
/ \
8 22
/ \
4 12
/ \ / \
13 1 10 14
Target Node = 12
K = 3
-> The first step is to find the DFS path to the target node.
[17]
/ \
[20] 15
/ \
[8] 22
/ \
4 [12]
/ \ / \
13 1 10 14
-> Now backtrack the DFS path with decreasing Kth value.
[17, 0]
/ \
[20, 1] 15
/ \
[8, 2] 22
/ \
4 [12, 3]
/ \ / \
13 1 10 14
-> The crucial part is that while backtracking, we know if we came from the left or right child.
If we came from the left child, then find all the Kth distance children from the right of the current node using DFS, and vice versa.
[17, 0]
/ \
[20, 1] 15
/ \
[8, 2] [22, 0]
/ \
[4,1] [12, 3]
/ \ / \
[13,0] [1,0] [1,2] [14,2]
-> Hence, our required answer is {1, 13, 17, 22}Time and Space Complexity
Code (C++)
Contribution and Support
Last updated