完全二叉树是每一层(除最后一层外)都是完全填充(即,节点数达到最大,第 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]]
【思路】:
广度优先拿到层次遍历序列,根据层次遍历序列创建数组。
因为完全二叉树是可以用数组来存的。这样找父亲的话会非常方便。
【代码】:
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
//返回一个层序遍历的数组,类型为TreeNode
var levelOrder = function(root) {
var que = [];
que.push(root);
var res = [-1];
while(que.length != 0){
let front = que.shift();
res.push(front)
if(front.left != null){
que.push(front.left);
}
if(front.right!=null){
que.push(front.right);
}
}
return res;
};
/**
* @param {TreeNode} root
*/
var CBTInserter = function(root) {
this.arr = levelOrder(root); //层序遍历数组
};
/**
* @param {number} v
* @return {number}
*/
CBTInserter.prototype.insert = function(v) {
let newNode = new TreeNode(v)
this.arr.push(newNode);
let parent = 0;
if((this.arr.length - 1) % 2 != 0){
// 这里下标搞得非常烦人
parent = Number.parseInt((this.arr.length - 1 ) / 2);
this.arr[parent].right = newNode;
}else{
parent = Number.parseInt((this.arr.length - 1)/ 2);
this.arr[parent].left = newNode;
}
return this.arr[parent].val;
};
/**
* @return {TreeNode}
*/
CBTInserter.prototype.get_root = function() {
if(this.arr.length == 0) return null;
return this.arr[1]
};
/**
* Your CBTInserter object will be instantiated and called as such:
* var obj = new CBTInserter(root)
* var param_1 = obj.insert(v)
* var param_2 = obj.get_root()
*/