题目:
完全二叉树是每一层(除最后一层外)都是完全填充(即,节点数达到最大,第 n 层有 2n-1 个节点)的,并且所有的节点都尽可能地集中在左侧。
设计一个用完全二叉树初始化的数据结构 CBTInserter,它支持以下几种操作:
CBTInserter(TreeNode root) 使用根节点为 root 的给定树初始化该数据结构;
CBTInserter.insert(int v) 向树中插入一个新节点,节点类型为 TreeNode,值为 v 。使树保持完全二叉树的状态,并返回插入的新节点的父节点的值;
CBTInserter.get_root() 将返回树的根节点。
示例 1:
输入:inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
输出:[null,1,[1,2]]
示例 2:
输入:inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
输出:[null,3,4,[1,2,3,4,5,6,7,8]]
提示:
最初给定的树是完全二叉树,且包含 1 到 1000 个节点。
每个测试用例最多调用 CBTInserter.insert 操作 10000 次。
给定节点或插入节点的每个值都在 0 到 5000 之间。
代码:
class CBTInserter {
TreeNode root;
Deque<TreeNode> queue;
public CBTInserter(TreeNode root) {
queue = new LinkedList<>();
this.root = root;
queue.offer(root);
}
public int insert(int v) {
TreeNode node = new TreeNode(v);
while (queue.peek().left != null && queue.peek().right != null) {
TreeNode temp = queue.poll();
queue.offer(temp.left);
queue.offer(temp.right);
}
if (queue.peek().left == null) {
queue.peek().left = node;
return queue.peek().val;
}
queue.peek().right = node;
return queue.peek().val;
}
public TreeNode get_root() {
return root;
}
}
解题思路:
首先这道题呢,是一个完全二叉树上添加节点的问题,首先呢要清楚完全二叉树是一个什么样的数据结构,如何向完全二叉树添加节点。了解了这些以后,我们就要找出按照层次遍历的顺序的第一个不满的节点,然后在他下面添加节点,并且返回他的值即可。层次遍历呢就要借助一个队列去完成,开始的时候把根节点放进去,然后遍历队列,当队头元素的左右节点都不为空的时候,取出队头元素,就把左右节点加入队列,直到找到不满的节点为止。
注意:
注意身体。