Google | L3 | Phone Screen
Anonymous User
6632

Given roots of 2 n-ary trees write code to merge them. Complete the following function:

class Node:
	name: str
	value: str
	children: List[Node]
	
def merge(t1: Node, t2: Node):

Merge Rules for n-ary Trees:

  1. Same Name, Same Level:
    If two nodes (t1 and t2) have the same name at the same level:
    The resulting node will have:

    • The children of both t1 and t2 combined and recursively merged.
    • The value from t2 (i.e., t2.value will replace t1.value).
      Example:
    T1: A: lambda
    	B: hello
    	D: guest
    		E: umbrella
    T2: A: theta
    	C: imp
    	B: hydrogen
    Result:
    	A: theta
    	B: hydrogen (T2's value)
    	D: guest
    		E: umbrella (from T1)
    	C: imp (from T2)
  2. No Corresponding Node to Merge (Different Name or No Match at Same Level):
    If a node in one tree (t1) has no corresponding node with the same name at the same level in the other tree (t2), that node will be added directly without any merge.
    The order of nodes should be maintained as it is in both trees.
    Example:

    T1: B: how
    T2: X: happy
    Result:
    X: 
    	B: how
    	X: happy
  3. Order Preservation:
    The order of the nodes at each level in the merged tree should be based on their original position in t1 and t2.
    Nodes from t1 should appear in their original order, followed by any nodes from t2 that were not merged.
    Example:

    T1: C: are
    T2: A: alpha
    
    Result:
    C: are
    A: alpha

Example:

T: hey
	A: lambda
		B: hello
		D: guest
			E: umbrella
	B: how
	C: are
	D: hey
	A: you	

T: approx
	B: humble
	A: theta
		C: imp
		B: hydrogen
	D: oxygen
	A: alpha
	X: happy

Result:
T: approx
	A: theta
		B: hydrogen
		D: guest
			E: umbrella
		C: imp
	B: humble
	C: are
	D: oxygen
	A: alpha
	X: happy

Note: I don't remember the exact question but it went something like this

Comments (7)