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
.
完全二叉树是每一层(除最后一层外)都是完全填充(即,结点数达到最大)的,并且所有的结点都尽可能地集中在左侧。
设计一个用完全二叉树初始化的数据结构 CBTInserter
,它支持以下几种操作:
CBTInserter(TreeNode root)
使用头结点为root
的给定树初始化该数据结构;CBTInserter.insert(int v)
将TreeNode
插入到存在值为node.val = v
的树中以使其保持完全二叉树的状态,并返回插入的TreeNode
的父结点的值;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
之间。
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class CBTInserter { 11 TreeNode root; 12 int cnt; 13 private int calc(TreeNode root) { 14 if (root == null) { 15 return 0; 16 } 17 return calc(root.left) + calc(root.right) + 1; 18 } 19 public CBTInserter(TreeNode root) { 20 this.root = root; 21 cnt = calc(root); 22 } 23 24 public int insert(int v) { 25 int cur = ++cnt; 26 int ipos = 31; 27 while ((cur & (1 << ipos)) == 0) { 28 ipos--; 29 } 30 ipos--; 31 TreeNode curNode = root; 32 while (ipos > 0) { 33 if ((cur & (1 << ipos)) == 0) { 34 curNode = curNode.left; 35 } else { 36 curNode = curNode.right; 37 } 38 ipos--; 39 } 40 if ((cur & (1 << ipos)) == 0) { 41 curNode.left = new TreeNode(v); 42 } else { 43 curNode.right = new TreeNode(v); 44 } 45 return curNode.val; 46 } 47 48 public TreeNode get_root() { 49 return root; 50 } 51 } 52 53 /** 54 * Your CBTInserter object will be instantiated and called as such: 55 * CBTInserter obj = new CBTInserter(root); 56 * int param_1 = obj.insert(v); 57 * TreeNode param_2 = obj.get_root(); 58 */