Encode N-ary Tree to Binary Tree – Python 3 (Week 13 – 01)

"""
class UndirectedGraphNode:
     def __init__(self, x):
         self.label = x
         self.neighbors = []Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: binary tree
    @return: N-ary tree
    """
    def decode(self, root):
        # write your code here
        if not root:
            return None
        naryTree = UndirectedGraphNode(root.val)
        #if root.left:
        #    naryTree.neighbors.append(self.decode(root.left))
            
        #cur = root.left
        #while cur and cur.right:
        #    cur = cur.right
        #    naryTree.neighbors.append(self.decode(cur))
        cur = root.left
        while cur:
            naryTree.neighbors.append(self.decode(cur))
            cur = cur.right
        
        
        
            
        return naryTree
        
        
        
        
    """
    @param root: N-ary tree
    @return: binary tree
    """
    def encode(self, root):
        # write your code here
        if not root:
            return None
            
        binaryTree = TreeNode(root.label)
        
        if root.neighbors:
            binaryTree.left = self.encode(root.neighbors[0])
        cur = binaryTree.left
        for i in range(1, len(root.neighbors)):
            cur.right = self.encode(root.neighbors[i])
            cur = cur.right
        return binaryTree
        

Time O(h). Space O(h).

Leave a comment

Design a site like this with WordPress.com
Get started