https://leetcode.com/problems/complete-binary-tree-inserter/
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:
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:
- The initial given tree is complete and contains between
1
and1000
nodes. CBTInserter.insert
is called at most10000
times per test case.- Every value of a given or inserted node is between
0
and5000
.
算法思路:
First, perform a breadth-first search to populate the queue with nodes that have 0 or 1 children, in number order.
Now when inserting a node, the parent is the first element of the queue, and we add this new node to our queue, and if the new node of its parent right child, then pop the parent node.
完全二叉树(complete binary tree)的插入操作(insert)借助于队列(queue)会在常数时间完成 -- O(1)。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class CBTInserter {
public:
CBTInserter(TreeNode* root) {
this->root = root;
queue<TreeNode*> q;
q.push(root);
TreeNode* node;
while(!q.empty()) {
node = q.front(); q.pop();
if (node->left == nullptr || node->right == nullptr) que.push(node);
if (node->left != nullptr) q.push(node->left);
if (node->right != nullptr) q.push(node->right);
}
}
int insert(int v) {
TreeNode* node = que.front();
que.push(new TreeNode(v));
if (node->left == nullptr) {
node->left = que.back();
} else {
node->right = que.back();
que.pop();
}
return node->val;
}
TreeNode* get_root() {
return root;
}
private:
// record the root.
TreeNode* root;
// when in bfs, save nodes that have 0 or 1 children, in number order.
queue<TreeNode*> que;
};
/**
* Your CBTInserter object will be instantiated and called as such:
* CBTInserter* obj = new CBTInserter(root);
* int param_1 = obj->insert(v);
* TreeNode* param_2 = obj->get_root();
*/