Sol:
This can be divided into two cases:
This can be divided into two cases:
- It is easy to print the nodes at distance K from node which are under the subtree of the given node. Pass an integer 'dist' to its children and increment it each time. When 'dist' == K, print those nodes.
- Nodes at distance K from the given node with its parent node in the path. For this we can return 'dist' in our recursive function. And increment it at each step before returning. When returned value at any point is K we print those nodes. Special case: If we are doing inorder traversal, we need to handle a special case when the given node is the right child of its parent. In this case we will have to traverse the left child of its parent again.
Data Science course is for smart people. Make the smart choice and reach the apex of your career. Learn the latest trends and techniques from the experts.
ReplyDeletedata science course