1. 程式人生 > >【LeetCode】919. Complete Binary Tree Inserter 解題報告(Python)

【LeetCode】919. Complete Binary Tree Inserter 解題報告(Python)

題目描述:

A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Write a data structure CBTInserter that is initialized with a complete binary tree and supports the following operations:

  • CBTInserter(TreeNode root)
    initializes the data structure on a given tree with head node root;
  • CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;
  • CBTInserter.get_root() will return the head node of the tree.

Example 1:

Input: inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
Output: [null,1,[1,2]]

Example 2:

Input: inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
Output: [null,3,4,[1,2,3,4,5,6,7,8]]

Note:

  1. The initial given tree is complete and contains between 1 and 1000 nodes.
  2. CBTInserter.insert is called at most 10000 times per test case.
  3. Every value of a given or inserted node is between 0 and 5000.

題目大意

編寫一個完全二叉樹的資料結構,需要完成構建、插入、獲取root三個函式。函式的引數和返回值如題。

解題方法

周賽第三題,因為第二題我不會,就把這個題給放棄了……現在一看很簡單啊。

完全二叉樹是每一層都滿的,因此找出要插入節點的父親節點是很簡單的。如果用陣列tree儲存著所有節點的層次遍歷,那麼新節點的父親節點就是tree[(N -1)/2],N是未插入該節點前的樹的元素個數。

構建樹的時候使用層次遍歷,也就是BFS把所有的節點放入到tree裡。插入的時候直接計算出新節點的父親節點。獲取root就是陣列中的第0個節點。

時間複雜度是O(N),空間複雜度是O(N)。

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class CBTInserter(object):

    def __init__(self, root):
        """
        :type root: TreeNode
        """
        self.tree = list()
        queue = collections.deque()
        queue.append(root)
        while queue:
            node = queue.popleft()
            self.tree.append(node)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

    def insert(self, v):
        """
        :type v: int
        :rtype: int
        """
        _len = len(self.tree)
        father = self.tree[(_len - 1) / 2]
        node = TreeNode(v)
        if not father.left:
            father.left = node
        else:
            father.right = node
        self.tree.append(node)
        return father.val
        

    def get_root(self):
        """
        :rtype: TreeNode
        """
        return self.tree[0]


# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(v)
# param_2 = obj.get_root()

參考資料:

日期

2018 年 10 月 7 日 —— 假期最後一天!!