LeetCode 919. Complete Binary Tree Inserter解題報告(python)

919. Complete Binary Tree Inserter

  1. Complete Binary Tree Inserter python solution

題目描述

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.
在這裏插入圖片描述

解析

完全二叉樹(Complete Binary Tree)
若設二叉樹的深度爲h,除第 h 層外,其它各層 (1~h-1) 的結點數都達到最大個數,第 h 層所有的結點都連續集中在最左邊,這就是完全二叉樹。

我們來看一個完全二叉樹

            5
        /         \
       2          100
    /    \      /    \
   1      3    99    101

然後現在先要插入4,如果我們不想破壞搜索性條件,那麼4就會變成3的右孩子,但是最後一層的節點就沒有集中在最左邊。

所以在這種情況下,N=7,則(N-1)/2 = 3, 樹的節點列表爲[5,2,100,1,3,99,101]。所以4便成爲1的左孩子

class CBTInserter:

    def __init__(self, root):
        self.tree = [root]
        for i in self.tree:
            if i.left: self.tree.append(i.left)
            if i.right: self.tree.append(i.right)

    def insert(self, v):
        N = len(self.tree)
        self.tree.append(TreeNode(v))
        if N % 2:
            self.tree[int((N - 1) / 2)].left = self.tree[-1]
        else:
            self.tree[int((N - 1) / 2)].right = self.tree[-1]
        return self.tree[int((N - 1) / 2)].val

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

        

Reference

https://leetcode.com/problems/complete-binary-tree-inserter/discuss/178424/C%2B%2BJavaPython-O(1)-Insert

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章