[LeetCode] Populate the next right pointer in binary tree I

注意,在leetcode的原题中,nextRight初始化为NULL。如果nextRight初始化为随机值,下面的方法也是适用的。

Populate the next right pointer in binary tree。 The next right pointer points to the next right node in the level-order traversal.

Given the structure of node in binary tree

structNode {
  Node* leftChild;
  Node* rightChild;
  Node* nextRight;
}

Populate the nextRight pointers in each node.
You may assume that it is a complete binary tree (ie, all leaf nodes are on the same level, and each node other than the leaves has two children.)

思路:

The first key to solving this problem is we have the nextRight pointer. Assume that the nextRight pointers are already populated for this level. How can we populate the next level? Easy… just populate by iterating all nodes on this level. Another key to this problem is you have to populate the next level before you go down to the next level, because once you go down, you have no parent pointer, and you would have hard time populating, as I mentioned in the observation I made earlier. 注意:该算法只适用于complete binary tree。对任意二叉树都适用的算法,请看这里

void connect(Node* p) {
  if (p == NULL)
    return;
  if (p->leftChild == NULL || p->rightChild == NULL)
    return;
  Node* rightSibling;
  Node* p1 = p;
  while (p1) {
    if (p1->nextRight)
      rightSibling = p1->nextRight->leftChild;
    else
      rightSibling = NULL;
    p1->leftChild->nextRight = p1->rightChild;
    p1->rightChild->nextRight = rightSibling;
    p1 = p1->nextRight;
  }
  connect(p->leftChild);
}

EDIT: (Added alternative solution)

Here is a more elegant solution. The trick is to re-use the populated nextRight pointers. As mentioned earlier, we just need one more step for it to work. Before we passed the leftChild and rightChild to the recursion function itself, we connect the rightChild’s nextRight to the current node’s nextRight’s leftChild. In order for this to work, the current node’s nextRight pointer must be populated, which is true in this case. Why? Try to draw a series of diagram how the recursion deepens, you will immediately see that it is doing DFS (Depth first search).

void connect(Node* p) {
  if (!p) return;
  if (p->leftChild)
  p->leftChild->nextRight = p->rightChild;
  if (p->rightChild)
    p->rightChild->nextRight = (p->nextRight) ?
                               p->nextRight->leftChild :
                               NULL;
  connect(p->leftChild);
  connect(p->rightChild);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值