[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);
}


你可能感兴趣的:([LeetCode] Populate the next right pointer in binary tree I)