Apple SDE | Phone Interview

Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2020-02-15Added By Anonymous
Source: Link

You have an integer list (unique values), what you need to do is build a tree met following conditions:


Binary tree

Each node value small than its children’ value


In-order traverse sequence same as the array list sequence

intput: [5, 3, 7, 4, 1, 2 ,6]

output

____1

__3___2

5___4____6

______7


1My Solution: 2class Node: 3 def __init__(self,val): 4 self.val=val 5 self.child1=None 6 self.child2=None 7 self.parent=None 8def construct(input): 9 if input==[]: 10 return None 11 root=Node(input[0]) 12 prev=root 13 for i in range(1,len(input)): 14 if input[i]<root.val: 15 temp=Node(input[i]) 16 temp.child1=root 17 root.parent=temp 18 prev=temp 19 root=temp 20 else: 21 if prev.val>input[i]: 22 temp=Node(input[i]) 23 temp_p=prev.parent 24 temp.child1=prev 25 temp.parent=temp_p 26 temp_p.child2=temp 27 prev.parent=temp 28 prev=temp 29 elif prev.child2==None: 30 temp=Node(input[i]) 31 temp.parent=prev 32 prev.child2=temp 33 prev=temp 34 return root 35 36def inorder(root): 37 if root==None: 38 return None 39 inorder(root.child1) 40 print(root.val) 41 inorder(root.child2) 42 return 43inorder(construct([1,2,3,4,5,6,7]))
Comments