919. Complete Binary Tree Inserter - LeetCode
A complete binary tree is one in which each level (except the last level) is completely populated (ie, the number of nodes reaches the maximum), and all nodes are concentrated on the left side as much as possible.
Design an algorithm that inserts a new node into a complete binary tree and keeps it intact after insertion.
Implementation CBTInserter
class:
CBTInserter(TreeNode root)
root
initialize the data structure with the given tree with head node as ;CBTInserter.insert(int v)
Node.val == val
Inserts a new node with value into the treeTreeNode
. Keep the tree in the state of a complete binary tree and returnTreeNode
the value of the inserted node's parent node ;CBTInserter.get_root()
Will return the head node of the tree.
Example 1:
Input ["CBTInserter", "insert", "insert", "get_root"] [[[1, 2]], [3], [4], []] Output [null, 1, 2, [1, 2] , 3, 4]] explain CBTInserter cBTInserter = new CBTInserter([1, 2]); cBTInserter.insert(3); // returns 1 cBTInserter.insert(4); // returns 2 cBTInserter.get_root(); // returns [1, 2, 3, 4]
hint:
- The number of nodes in the tree ranges from
[1, 1000]
0 <= Node.val <= 5000
root
is a complete binary tree0 <= val <= 5000
- Maximum calls
insert
andget_root
operations per test case104
import java.util.LinkedList;
import java.util.Queue;
class CBTInserter {
// 使用队列按顺序保存只有1个或没有子节点的节点,然后每次从队列头取一个节点创建新节点(先左节点后右节点)
Queue<TreeNode> data;
TreeNode root;
public CBTInserter(TreeNode root) {
this.root = root;
Queue<TreeNode> queue = new LinkedList<>();
data = new LinkedList();
queue.offer(root);
// 找到所有符合插入条件的节点
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
// 把所有符合插入条件的节点放到队列data中
if (node.left == null || node.right == null) {
data.offer(node);
}
}
}
public int insert(int val) {
TreeNode d = new TreeNode();
d.val = val;
data.offer(d);
TreeNode first = data.peek();
// 先插入左节点
if (first.left == null) {
first.left = d;
}
// 然后插入左节点
else if (first.right == null) {
first.right = d;
data.poll();
} else {
// 理论不存在该情况
data.poll();
}
return first.val;
}
public TreeNode get_root() {
return root;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
}