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.
4 5 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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print nodes at k distance from root | Iterative
- Count of nodes which are at a distance X from root and leaves
- Find distance of nodes from root in a tree for multiple queries
- Find node U containing all nodes from a set V at atmost distance 1 from the path from root to U
- Print the path common to the two paths from the root to the two given nodes
- Print common nodes on path from root (or common ancestors)
- Print path from root to all nodes in a Complete Binary Tree
- Find if there is a pair in root to a leaf path with sum equals to root's data
- Print all nodes that are at distance k from a leaf node
- Print all nodes at distance k from a given node
- Print all neighbour nodes within distance K
- Print all nodes at distance K from given node: Iterative Approach
- Find distance from root to given node in a binary tree
- Iterative program to find distance of a node from root
- Print levels with odd number of nodes and even number of nodes
- Count of Root to Leaf Paths consisting of at most M consecutive Nodes having value K
- Remove nodes on root to leaf paths of length < K
- Sum of nodes on the longest path from root to leaf node
- Root to leaf path with maximum distinct nodes
- Check if two nodes are in same subtree of the root node