完全二叉树是每一层(除最后一层外)都是完全填充(即,节点数达到最大,第 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]]
提示:
- //leetcode submit region begin(Prohibit modification and deletion)/** * Definition for a binary tree node. * 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; * } * } */class Solution { public List
largestValues(TreeNode root) { List result = new ArrayList<>(); Queue nodeQ = new LinkedList<>(); if (root == null) { return result; } int nodeNum = 1; nodeQ.add(root); while (!nodeQ.isEmpty()) { int maxNum = Integer.MIN_VALUE; for (int i = 0; i < nodeNum; i++) { TreeNode node = nodeQ.poll(); if (node.val > maxNum) { maxNum = node.val; } if (node.left != null) { nodeQ.add(node.left); } if (node.right != null) { nodeQ.add(node.right); } } nodeNum = nodeQ.size(); result.add(maxNum); } return result; }}//leetcode submit region end(Prohibit modification and deletion)java - 每个测试用例最多调用
CBTInserter.insert
操作10000
次。 - 给定节点或插入节点的每个值都在
0
到5000
之间。
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* 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;
* }
* }
*/
class CBTInserter {
Queue<TreeNode> nodeQ;
TreeNode root;
public CBTInserter(TreeNode root) {
nodeQ = new LinkedList<>();
this.root = root;
nodeQ.add(root);
while (nodeQ.peek().left != null) {
nodeQ.add(nodeQ.peek().left);
if (nodeQ.peek().right != null) {
nodeQ.add(nodeQ.poll().right);
} else {
break;
}
}
}
public int insert(int v) {
TreeNode newNode = new TreeNode(v);
int result = nodeQ.peek().val;
if (nodeQ.peek().left == null) {
nodeQ.peek().left = newNode;
} else {
nodeQ.poll().right = newNode;
}
nodeQ.add(newNode);
return result;
}
public TreeNode get_root() {
return this.root;
}
}
/**
* 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();
*/
//leetcode submit region end(Prohibit modification and deletion)