LC 117. Populating Next Right Pointers in Each Node II

Leetcode 117. Populating Next Right Pointers in Each Node II

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

Approach 1: Level Order Traversal
有三种BFS: PreOrder, InOrder, PostOrder、
BFS探索tree基于节点的level , level 是当前node距离root的长度。

Algorithm

  • 初始化Queue,
    (1) 像Queue添加pair(node.val, node.level), 可以继续添加(node.left.val,
    node.level+1) 和 (node.right.val, node.level+1)
    (2) 用NULL 分割,用Null作为一个level的结束标志。配合while loop 遍历queue。
while (!Q.empty())
    {
        size = Q.size()
        for i in range 0..size
        {
            node = Q.pop()
            Q.push(node.left)
            Q.push(node.right)
        }
    }
  • 添加(root, level == 0)
  • pop(node,level)的同时, 添加(node.left, level+1) 和(node.right, level+1),重复queue.size() 次。

time complexity: O(N) ; space complexity: O(N)

Approach 2: Using previously established next pointers
We only move on to the level N+1 when we are done establishing the next pointers for the level N.

Node prev, leftmost; // public variables

Algorithm

定义三个变量:

  • leftmost: represents the corresponding variable on each level.
  • curr: It starts off with leftmost and then follows the next pointers all the way to the very end.
  • prev: This is the pointer to the leading node on the next level.
leftmost = root
while (leftmost != null)
{
    curr = leftmost
    prev = NULL
    while (curr != null)
    {
        → process left child
        → process right child
        → set leftmost for the next level
        curr = curr.next
    }
}

For example:

level N : 2 -> 3 -> 5 -> 8
level N+1: 4, null, null, 6, 12, null, null, 10

  • curr = NULL, leftmost = node 2, prev = node 4
  • curr = node 3, leftmost = node 4, prev = node 6 (4->6)
  • curr = node 5, leftmost = node 4, prev = node 12 (4->6->12)
  • curr = node 9, leftmost = node 4, prev = node 10 (4->6->12->10)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值