leetcode:Populating Next Right Pointers in Each Node

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

좋은 웹페이지 즐겨찾기