思路
层序遍历二叉树,然后把结点插入到第一个发现的子节点没有都填充满的结点下方。具体的实现思路可以用队列。注意如何加快添加速度的方式~
class CBTInserter {
TreeNode root;
Queue<TreeNode> queue;
public CBTInserter(TreeNode root) {
this.root = root;
queue = new LinkedList<>();
queue.offer(root);
while (null != queue.peek().left && null != queue.peek().right) {
TreeNode node = queue.poll();
queue.offer(node.left);
queue.offer(node.right);
}
}
public int insert(int v) {
TreeNode node = new TreeNode(v), parent;
if (null == queue.peek().left) {
parent = queue.peek();
parent.left = node;
} else {
parent = queue.poll();
parent.right = node;
queue.offer(parent.left);
queue.offer(parent.right);
}
return parent.val;
}
public TreeNode get_root() {
return root;
}
}
Go代码
type CBTInserter struct {
root *TreeNode
q []*TreeNode
}
func Constructor(root *TreeNode) CBTInserter {
q := []*TreeNode{root}
for q[0].Left != nil && q[0].Right != nil {
node := q[0]
q = append(q, node.Left)
q = append(q, node.Right)
q = q[1:]
}
if q[0].Left != nil {
q = append(q, q[0].Left)
}
if q[0].Right != nil {
q = append(q, q[0].Right)
}
return CBTInserter{
root: root,
q: q,
}
}
func (this *CBTInserter) Insert(v int) int {
parent := this.q[0]
node := &TreeNode{
Val: v,
Left: nil,
Right: nil,
}
if parent.Left == nil {
parent.Left = node
} else {
parent.Right = node
this.q = this.q[1:]
}
this.q = append(this.q, node)
return parent.Val
}
func (this *CBTInserter) Get_root() *TreeNode {
return this.root
}