Meta Interview Question

Questions - Print all paths in a binary tree - Function to find the square root of a number - Pretty print JSON object - How would you design home feed? - Simple regex matcher

Interview Answers

Anonymous

Feb 14, 2015

class TreeNode(object): def __init__(self, v, l=None, r=None): self.v = v self.l = r self.r = l def get_paths(self, path=[]): result = [] new_path = path[:] new_path.append(self.v) if self.l is None and self.r is None: return [new_path] if self.l != None: result += self.l.get_paths(new_path) if self.r != None: result += self.r.get_paths(new_path) return result # 4 # /\ # 3 6 # /\ /\ # 8 9 7 2 # / \ #1 0 a1 = TreeNode(1) a8 = TreeNode(8, a1) a0 = TreeNode(0) a9 = TreeNode(9, r=a0) a3 = TreeNode(3, a8, a9) a7 = TreeNode(7) a2 = TreeNode(2) a6 = TreeNode(6, a7, a2) root = TreeNode(4, a3, a6) print root.get_paths()

Anonymous

Feb 14, 2015

def square_root(num, precission=0.001): pow_two = 1 x = num while abs(num-pow_two) > precission: pow_two = x*x x -= (pow_two - num) / (2.0 * x) return x print square_root(4) print square_root(10) print square_root(3)

Anonymous

May 3, 2015

printing all path in binary tree //printing all the path from root to leaf using recursion public void printRooToLeaf(Node X,List Path){ if(X==null) return; Path.add(X); printRooToLeaf(X.leftChild,Path); printRooToLeaf(X.rightChild,Path); if(X.leftChild==null && X.rightChild==null) { System.out.println("print path from root :"+ root.a+"to leaf"+X.a); for(Node y:Path){ System.out.println(""+y.a); } System.out.println(); } Path.remove(Path.size()-1); }