Populating Next Right Pointers in Each Node II

来源:互联网 发布:数控西门子系统编程 编辑:程序博客网 时间:2024/05/16 10:18
<pre name="code" class="cpp">/** * Definition for binary tree with next pointer. * struct TreeLinkNode { *  int val; *  TreeLinkNode *left, *right, *next; *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public:    void connect(TreeLinkNode *root)     {                if(!root)              return;          TreeLinkNode* lastHead = root;          TreeLinkNode* pre = NULL;          TreeLinkNode* curHead = NULL;          while(lastHead)          {              TreeLinkNode* lastCur = lastHead;              while(lastCur)              {                  if(lastCur->left)                  {                      if(curHead == NULL)                      {                          curHead = lastCur->left;                          pre = curHead;                      }                      else                    {                          pre->next = lastCur->left;                          pre = pre->next;                      }                  }                  if(lastCur->right)                  {                      if(curHead == NULL)                      {                          curHead = lastCur->right;                          pre = curHead;                      }                      else                    {                          pre->next = lastCur->right;                          pre = pre->next;                      }                  }                                  lastCur = lastCur->next;                   }              lastHead = curHead;              curHead = NULL;          }      }};

代码同样适用于Populating Next Right Pointers in Each Node,感谢Code_Ganker 
                                             
0 0
原创粉丝点击