Given a root of a tree, and an integer k. Print all the nodes which are at k distance from root.
For example, in the below tree, 4, 5 & 8 are at distance 2 from root.
1 / \ 2 3 / \ / 4 5 8
The problem can be solved using recursion. Thanks to eldho for suggesting the solution.
The above program prints 4, 5 and 8.
Time Complexity: O(n) where n is number of nodes in the given binary tree.
Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.
- Print nodes at k distance from root | Iterative
- Print the path common to the two paths from the root to the two given nodes
- Print all nodes at distance k from a given node
- Print all nodes that are at distance k from a leaf node
- Print common nodes on path from root (or common ancestors)
- Find distance from root to given node in a binary tree
- Iterative program to find distance of a node from root
- Check if two nodes are in same subtree of the root node
- Sum of nodes on the longest path from root to leaf node
- Root to leaf path with maximum distinct nodes
- Remove nodes on root to leaf paths of length < K
- Find distance between two nodes of a Binary Tree
- Distance between two nodes of binary tree with node values from 1 to N
- Queries to find distance between two nodes of a Binary tree
- Shortest distance between two nodes in an infinite binary tree