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.
LeetCode 919. Complete Binary Tree Inserter解题报告(python)_第1张图片

解析

完全二叉树(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

你可能感兴趣的:(LeetCode)