首页 > 代码库 > Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

Problem:Populating Next Right Pointers in Each Node

Given a binary tree:
struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).



class Solution {
public:
    void connect(TreeLinkNode *root) {
        TreeLinkNode * parent_p, *pCur, *leftmost;
        if(!root)
            return;
        parent_p = root;//保存当前结点的父结点
        pCur = root->left;//当前处理结点
        leftmost = pCur;//指向每一层最左边的结点
        while(pCur)
        {
            if(pCur == parent_p->left)//当前结点是其父结点的左孩子
            {
                pCur->next = parent_p->right;
                pCur = pCur->next;
            }
            else if(parent_p->next)//当前结点是其父结点的右孩子,并且父结点的next结点存在
            {
                parent_p =parent_p->next;
                pCur->next = parent_p->left;
                pCur = pCur->next;
            }
            else//当前层的所有结点全部处理完,转到下一层继续处理
            {
                parent_p = leftmost;
                leftmost = pCur = parent_p->left;
            }
        }
        
    }
};