问题描述:
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 node root;
CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;
CBTInserter.get_root() will return the head node of the tree.
解决方法:
对于CBTInserter(TreeNode root),众所周知,如果给定一颗树,需要按层遍历的话,可以用队列来模拟。
对于CBTInserter.insert(int v),我们可以用一个vector来模拟树,假设树的编号从根开始是1,然后逐层增加,那么你会发现,一个节点的左孩子编号是该节点编号*2, 一个节点的右孩子编号是该节点编号*2+1,反之一个节点的父亲节点编号是该节点编号/2.大家可以自行画下体会一下。
代码:
class CBTInserter {
public:
vector<TreeNode*>a;
CBTInserter(TreeNode* root) {
a.clear();
a.push_back(NULL);//为了让根节点编号为1
queue<TreeNode*>q;
q.push(root);
while(!q.empty())
{
TreeNode *now=q.front();q.pop();
a.push_back(now);
if(now->left!=NULL)q.push(now->left);
if(now->right!=NULL)q.push(now->right);
}
}
int insert(int v) {
TreeNode *b=new TreeNode(v);
int len=a.size();
if(len%2==0)
a[len/2]->left=b;
else a[len/2]->right=b;
a.push_back(b);
return a[len/2]->val;
}
TreeNode* get_root() {
return a[1];
}
};