Interview Question
Country: United States
def getDepth(node, value) {
if node.value == value :
return 0;
return 1 + max(getDepth(node.left), getDepth(node.right));
}
def getNodesOfDepth(node, depth, desired_depth) {
if depth == desired_depth:
return [node.value];
nodes = getNodesOfDepth(node.left, depth + 1, desired_depth);
nodes.extend(getNodesOfDepth(node.right, depth + 1, desired_depth));
return nodes
}
def F(node, value, distance) {
depth = getDepth(node, value)
result = getNodesOfDepth(depth - distance)
result.extend(getNodesOfDepth(depth + distance))
return result
}
def getDepth(node, value) {
if node is None :
return 0
if node.value == value :
return 0
return 1 + max(getDepth(node.left), getDepth(node.right));
}
def getNodesOfDepth(node, depth, desired_depth) {
if node is None :
return []
if depth == desired_depth:
return [node.value];
nodes = getNodesOfDepth(node.left, depth + 1, desired_depth);
nodes.extend(getNodesOfDepth(node.right, depth + 1, desired_depth));
return nodes
}
def F(node, value, distance) {
depth = getDepth(node, value)
result = getNodesOfDepth(depth - distance)
result.extend(getNodesOfDepth(depth + distance))
return result
}
(root,7,1) will return 5
(root,7,2) will return 4
Let the parameters are root_node, target_node, K (distance)
Traverse the tree - recursive calls (inorder traversal)
If a node is the target node then print all the child nodes at distance K from target node.
While returning from a recursive call, return the distance of node from target node. If target is not yet found, return -1.
Use the distance returned to print the nodes at (k-returned_distance-2) in the other subtree via another recursive call.
Note:
If returned value to current node is X (X != -1) then target node is at distance x+1 in that subtree.
In other subtree, required nodes will be at distance (K-X-1) from current node or we can say
required nodes will be at distance (K-X-2) from root of other subtree as root of other subtree is
child of current node.
- Cerberuz August 31, 2014