Given a binary tree and a positive integer k, return all nodes that are exactly k distance away from any leaf node. A leaf node is a node with no children.
OR
Given a binary tree and a positive integer k, print all nodes that are exactly k distance away from any leaf node. A leaf node is a node with no children.
Input: root =[1,2,3,4,5,null,6,7,8,null,null,9,10], k =2Output: [1,2,3]Explanation:
Nodes at a distance of 2 from any leaf nodes(7,8,5,9,10) are 1 and 3.- Distance 2 from leaf 7: Node 4->2- Distance 2 from leaf 8: Node 4->2- Distance 2 from leaf 5: Node 2->1- Distance 2 from leaf 9: Node 6->3- Distance 2 from leaf 10: Node 6->3
classSolution:
defnodesAtDistanceKFromLeaf(self, root: Optional[TreeNode], k: int) -> List[int]:
defdfs(node: TreeNode, k: int, path: List[TreeNode], unique_nodes: Set[TreeNode]) ->None:
ifnot node:
return# Add current node to the path path.append(node)
# Check if leaf nodeifnot node.left andnot node.right:
if len(path) > k:
unique_nodes.add(path[-k-1])
# Recur for left and right children dfs(node.left, k, path, unique_nodes)
dfs(node.right, k, path, unique_nodes)
# Remove current node from the path on return path.pop()
unique_nodes = set()
ans = []
dfs(root, k, [], unique_nodes)
return [node.val for node in unique_nodes]
⏰ Time complexity: O(n), where n is the number of nodes in the tree because each node is visited once.
🧺 Space complexity: O(h + m), where h is the maximum depth of the tree (for the recursion stack) and m is the number of unique nodes at distance k from leaf nodes (for the result storage).