LeetCode[117] Population Next Right Pointers in Each Node II

发布时间:2019-06-08 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了LeetCode[117] Population Next Right Pointers in Each Node II脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

LeetCode[117] Population Next Right Pointers in Each Node II

     1
   /  
  2    3
 /     
4   5    7



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

Iteration

复杂度
O(N),O(1)

思路
设置一个dummy node 指向下一层要遍历的节点的开头的位置。

代码

public void connect(TreeLinkNode root) {
    TreeLinkNode dummy = new TreeLinkNode(0);
    TreeLinkNode pre = dummy;
    while(root != null) {
        if(root.left != null) {
            pre.next = root.left;
            pre = pre.next;
        }
        if(root.right != null) {
            pre.next = root.right;
            pre = pre.next;
        }
        root = root.next;
        // done with the search of current level
        if(root == null) {
            root = dummy.next;
            pre = dummy;
            dummy.next = null;
        }
    }

}

脚本宝典总结

以上是脚本宝典为你收集整理的LeetCode[117] Population Next Right Pointers in Each Node II全部内容,希望文章能够帮你解决LeetCode[117] Population Next Right Pointers in Each Node II所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: