📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
查看: 2095| 回复: 1
跳转到指定楼层
上一主题 下一主题
收起左侧

[树/链表/图] Populating Next Right Pointers in Each Node I, II 疑问

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
网上找到一个解法,没看太懂,请给指点一下


特别是这一句话:dummy停留在next level的开头


http://wlcoding.blogspot.com/2015/03/populating-next-right-pointers-in-each.html?view=sidebar








两道题可以用一个算法解决。


Time ~ O(N), Space ~ O(1)
逐行完成connection:
                         1 -> NULL
                       /    \
                     2  -> 3 -> NULL         curr moves from left to right (current level)
                    /  \      /  \
dummy -> 4->5->6->7 -> NULL    prev moves from left to right (next level)
注意:
  • prev = dummy 和接下来的 prev.next = curr.left or curr.right 使 dummy停留在next level的开头,然后用 prev = prev.next 将 prev 从左向右移动。
  • connect完一行(next level)后,调用 connect(dummy.next) 进入下一行(记得此时 dummy.next 为next level的开头)。

public void connect(TreeLinkNode root) {    if (root == null)   return;    // dummy is the node above curr    // dummy.next stores the leftmost node in the next level    TreeLinkNode dummy = new TreeLinkNode(0);    TreeLinkNode prev = dummy, curr = root;    while (curr != null) {        // when curr has any child:        // if it's the leftmost node, connect dummy.next to it         // otherwise. connect previous left node to it        if (curr.left != null) {            prev.next = curr.left;            prev = prev.next;        }        if (curr.right != null) {            prev.next = curr.right;            prev = prev.next;        }        curr = curr.next;    }    connect(dummy.next);    // go down to the next level}

上一篇:List 的 clone()
下一篇:请教一个dfs复杂度计算的问题
🔗
 楼主| oio14644 2015-8-7 13:10:45 | 只看该作者
全局:
public void connect(TreeLinkNode root) {
    if (root == null)   return;
    // dummy is the node above curr
    // dummy.next stores the leftmost node in the next level
    TreeLinkNode dummy = new TreeLinkNode(0);
    TreeLinkNode prev = dummy, curr = root;
    while (curr != null) {
        // when curr has any child:
        // if it's the leftmost node, connect dummy.next to it
        // otherwise. connect previous left node to it
        if (curr.left != null) {
            prev.next = curr.left;
            prev = prev.next;
        }
        if (curr.right != null) {
            prev.next = curr.right;
            prev = prev.next;
        }
        curr = curr.next;
    }
    connect(dummy.next);    // go down to the next level
}
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表