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

leetcode:Populating Next Right Pointers in Each Node

时间:2015-04-04 09:17:58      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:tree   层序遍历   leetcode   

/**
 * 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) {
        queue<pair<TreeLinkNode*,int>> q;
        TreeLinkNode *pre = root;
        int num = 0;//标记上次访问节点的层数
        if(!root)
            return;
        q.push(pair<TreeLinkNode*,int>(root,1));
        while(!q.empty())
        {
            pair<TreeLinkNode*,int> p = q.front();
            q.pop();
            if(p.second==num)
                pre->next = p.first;
            pre = p.first;
            num = p.second;
            if(p.first->left)
                q.push(pair<TreeLinkNode*,int>(p.first->left,(p.second+1)));
            if(p.first->right)
                q.push(pair<TreeLinkNode*,int>(p.first->right,(p.second+1)));
        }
        pre = NULL;
    }
};

leetcode:Populating Next Right Pointers in Each Node

标签:tree   层序遍历   leetcode   

原文地址:http://blog.csdn.net/majing19921103/article/details/44859239

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