How to Serialize Binary Tree

后端 未结 10 910
野的像风
野的像风 2020-12-23 21:09

I went to an interview today where I was asked to serialize a binary tree. I implemented an array-based approach where the children of node i (numbering in level-order trave

10条回答
  •  清酒与你
    2020-12-23 21:26

    I am not using pre-order but I am using BFS. This is a question from leetcode

    Majority of people implementation are incorrect when using pre-order: the expected result should be

    "[1,2,3,null,null,4,5]", but instead majority people print the output as "[1,2,3,null,null,4,5,null,null]" since they are not counting the levels.

    Here is my implementation with the correct result.

    class Node(object):
        def __init__(self,data):
            self.left = None
            self.right = None
            self.data = data
    
    def serialize(root):
            queue = [(root,0)]
            result = []
            max_level_with_value = 0
            while queue:
                (node,l) = queue.pop(0)
                if node:
                    result.append((node.data,l))
                    queue.extend([(node.left,l+1),
                                  (node.right,l+1)
                                  ])
                    max_level_with_value = max(max_level_with_value,l)
                else:
                    result.append(('null',l))
            filter_redundant(result,max_level_with_value)
    
    
    def filter_redundant(result,max_level_with_value):
        for v,l in result:
            if l<= max_level_with_value:
                print(v)
    
    
    
    
    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)
    root.right.left = Node(4)
    root.right.right = Node(5)
    serialize(root)
    

提交回复
热议问题