919. Complete Binary Tree Inserter
https://leetcode.com/problems/complete-binary-tree-inserter/description/
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 noderoot
;CBTInserter.insert(int v)
will insert aTreeNode
into the tree with valuenode.val = v
so that the tree remains complete, and returns the value of the parent of the insertedTreeNode
;CBTInserter.get_root()
will return the head node of the tree.
Example 1:
Example 2:
Thoughts
实现初始和插入完全二叉树。完全二叉树存储方法是数组。2i + 1是左儿子,2i + 2是右儿子。因此(I - 1) / 2是parent,当插入的新node i%2是1时为parent的左节点,否则是右节点。
Code
Last updated
Was this helpful?