populating-next-right-pointers-in-each-node-ii

48 篇文章 0 订阅
11 篇文章 0 订阅

1、populating-next-right-pointers-in-each-node-ii 来源:牛客网

Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.

For example,
Given the following binary tree,
         1
       /  \
      2    3
     / \    \
    4   5    7

After calling your function, the tree should look like:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL

2、思路:

  • 代码1思路,采用队列,对于每一层的元素,遍历时,用一个临时的结点cur放置当前poll出来的结点,poll后,检查当前队列的对头是否是该层元素,若是用cur指向就可以了;
  • 代码2思路,不使用队列(题目说是You may only use constant extra space)。首先不使用队列的情况下我们要遍历整个树,就得利用它每一层都有一条链,有链就可以通过一个结点遍历一层了。这里通过新建头部结点tmpLevelFirst(该结点本身的值和树没关系,只有tmpLevelFirst.next来指向每一层的头结点)来实现

3、代码1,用队列辅助实现:

public class BFSConnectTree {
    public void connect(TreeLinkNode root) {
        if(root == null)
            return;
        Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
        queue.add(root);
        TreeLinkNode node = new TreeLinkNode(0);
        while(!queue.isEmpty()){
            int broad_size  = queue.size();//每一层 的节点数目
            for(int i = 0; i < broad_size; i++){
                node = queue.poll();
                if(i == broad_size - 1){//若是当前层的最后一个元素手动指向null
                    node.next = null;
                }else{
                    node.next = queue.peek();
                }
                if(node.left != null)
                    queue.add(node.left);
                if(node.right != null)
                    queue.add(node.right);
            }
        }

    }

}

代码2,利用每层都是链的特点实现:

public class BFSConnectTreeWithoutSpace {
    public void connect(TreeLinkNode root) {
        while (root != null) {
            //tmpLevelFirst为新建立的每层第一个节点(为了方便后面遍历当前行节点)
            TreeLinkNode tmpLevelFirst = new TreeLinkNode(0);
            TreeLinkNode cur = tmpLevelFirst;
            while (root != null) {
                if (root.left != null) {
                    cur.next = root.left;
                    cur = cur.next;
                }
                if (root.right != null) {
                    cur.next = root.right;
                    cur = cur.next;
                }
                root = root.next;
            }
            root = tmpLevelFirst.next;
        }
    }
}

注:代码和思路都参考了上面链接中的答案,非常感谢那些大佬

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值