Amazon Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
It's not clear to me what we need to do when the we are returning the middle of the tree.
If the specified height starts from 0 then:
class Node:
left , right, data = None, None, 0
def __init__(self, data, l, r):
# initializes the data members
self.left = l
self.right = r
self.data = data
def copyToH(n, h, H):
if h <= H:
lc = copyToH(n.left, h+1, H)
rc = copyToH(n.right, h+1, H)
return new Node(n.data, lc, rc)
else: return None
Question not clear. I suppose you want to traverse a specific interval of a binary tree. The code is pre-order traversal.
public static void traverseByInterval(BinaryTreeNode root, int l, int h) {
if (root == null) {
return;
}
if (l > h) {
return;
}
if (l <= 0 && h >= 0) {
System.out.print(root.data + " ");
}
traverseByInterval(root.left, l - 1, h - 1);
traverseByInterval(root.right, l - 1, h - 1);
}
For the second example, how are you supposed to merge subtrees to form a single tree?
- Anonymous February 22, 2012