剑指offer 专项突破版 43、往完全二叉树添加节点

题目链接

思路

层序遍历二叉树,然后把结点插入到第一个发现的子节点没有都填充满的结点下方。具体的实现思路可以用队列。注意如何加快添加速度的方式~

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
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值