问题描述:
- 实现
CBTInserter
类的操作:
CBTInserter(TreeNode root)
使用完全二叉树 root
来对该数据结构进行初始化。CBTInserter.insert(int v)
向该数据结构插入一个值为 v
的新节点,插入后仍保持完全二叉树状态,并且返回插入节点的父节点的值。CBTInserter.get_root()
返回完全二叉树的头节点。
解题思路:
- 用数组来保存完全二叉树。【数组的索引可以用来确定节点在完全二叉树中的顺序】
- 插入一个新值,就相当于在数组尾部插入一个节点,然后根据索引计算得到
parent
的索引。 - 还要将当前新值连接到真正的树上,找到
parent
索引之后,就可以根据当前索引是奇数还是偶数来判断是连接到 parent
的左子还是右子。【因为 root
是索引 0
,所以当前索引为奇数则是父节点的左子,当前索引为偶数则是父节点的右子】
代码实现:
class CBTInserter
{
private:
vector<TreeNode*> vec;
public:
CBTInserter(TreeNode* root)
{
queue<TreeNode*> q;
q.push(root);
while(!q.empty())
{
int sz = q.size();
while(sz-- > 0)
{
TreeNode* tmp = q.front(); q.pop();
vec.push_back(tmp);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
}
}
int insert(int val)
{
vec.push_back(new TreeNode(val));
int idx = vec.size() - 1;
int parent_idx = (idx - 1) / 2;
if(idx & 1) vec[parent_idx]->left = vec[idx];
else vec[parent_idx]->right = vec[idx];
return vec[parent_idx]->val;
}
TreeNode* get_root()
{
return vec[0];
}
};