## Interview Question

Country: United States

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````def find_node_with_value(root,node_value){
stack = list()
stack.push(root)
while ( !empty(stack) ){
node = stack.pop()
if ( node_value == node.value ){
return node
}
if ( node.left != null ){
stack.push(node.left)
}
if ( node.right != null ){
stack.push(node.right)
}
}
return null
}
// i have an implicit root
def find(x,y){
x_node = find_node_with_value(root ,x)
if ( x_node == null ) return false
y_node = find_node_with_value(x_node ,y)
y_node != null // return this
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

if y is contained in one of the 2 possible subtrees of x then x becomes LCA of x and y

Comment hidden because of low score. Click to expand.
0
of 0 vote

Thank you for the reply, but this is not recursion.

Comment hidden because of low score. Click to expand.
0
of 0 vote

Can you please restate the problem:
Do you want to know, if there is a subtree D in the tree T that has value x in the root of D and value y somewhere in D. If you write binary tree you assume no BST (no order)?

In this case something like:

``````def find(root, values, i):
if root is None: return False
if root.value == values[i]: i = i - 1
if i < 0: return True
return find(root.left, v, i) or find(root.right, v, i)

def find_if_descendant(root, x, y):
return find(root, [x, y], 1)``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

@ChrisK thank you for the solution, this is sth more like that that I was looking for... maybe I took the question too literally.. maybe I could have used a recursive method in the background, and my initial method would have contained only 2 arguments.

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.