码迷,mamicode.com
首页 > 其他好文 > 详细

Populating Next Right Pointers in Each Node

时间:2014-05-15 19:29:18      阅读:349      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   ext   

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


Populating Next Right Pointers in Each Node,布布扣,bubuko.com

Populating Next Right Pointers in Each Node

标签:style   blog   class   code   c   ext   

原文地址:http://blog.csdn.net/wan_hust/article/details/25895213

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!