FTPrep, 116 Populating Next Right Pointers in Each Node, TODO,再多code几遍,虽然总结写得还比较ok,但是还是手感不熟

代码:

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        TreeLinkNode levelHead=root;
        while(levelHead!=null){  // exactly the same with while(!currLevel.isEmpty()){...}
            TreeLinkNode curr=levelHead;  // always have the variable recording the head of the level
            while(curr!=null){            // if there is any node on this level, BFS
                if(curr.left!=null) curr.left.next=curr.right;
                if(curr.right!=null && curr.next!=null) curr.right.next=curr.next.left;
                curr=curr.next; // move to the right on the same level. 在第一层没有发生,因为只有一个节点,第一个也是最后一个。这个递归是走到每一层的最后一个。
            }
            levelHead=levelHead.left;   // move from the first node in this level to the next level.
        }
    }
}

// 这道题和 level traversal类似,但是在数据结构上 和输入输出上还是有挺大差别,两题的代码中可以找到对应逻辑,比如while()之类的,所以在generalize 两者还是可以的。但是!!在具体操作上还是应该把这题作为特例。
// 其实每一层的遍历对该层都没有进行处理,只是走完该层,同时把下一层的各个相邻节点连接起来!有点意思,自身不做处理,处理下一层!!怎么实现?从root开始啊,第一层只有一个节点,所以没有next,但是root有左右子节点,这样就可以把第2层链接起来了。下一个循环到第二层,过一遍,把第3层链接起来了,再进入第3层。 所以是 把下一层链接好了,再进入下一层,层与层之间的联系就是通过left,right实现的,同层之间的联系是通过next是实现的,单向实现!
// 这和我们之前的 level traversal是不是确实不一样。不需要额外的空间。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值