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 all nodes at distance k from a given node
- Print all nodes that are at distance k from a leaf node
- Difference between sums of odd level and even level nodes of a Binary Tree
- Tree Isomorphism Problem
- Connect nodes at same level
- Check if a binary tree is subtree of another binary tree | Set 1
- Print Ancestors of a given node in Binary Tree
- Get Level of a node in a Binary Tree
- Applications of tree data structure
- Foldable Binary Trees
- Maximum width of a binary tree
- Given a binary tree, print all root-to-leaf paths
- Level Order Tree Traversal
- Convert a Binary Tree into its Mirror Tree
- Write a Program to Find the Maximum Depth or Height of a Tree