116. Populating Next Right Pointers in Each Node

来源:互联网 发布:怎么发淘宝优惠券赚钱 编辑:程序博客网 时间:2024/05/21 03:57
/** * 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;        queue<TreeLinkNode *> q1;        q1.push(root);        int i=1;        int mark=2;        while(!q1.empty())        {            TreeLinkNode * a=q1.front();            q1.pop();            if(a->left) q1.push(a->left);            if(a->right) q1.push(a->right);            if(i+1==mark)            {                a->next=NULL;                mark*=2;            }            else            {                a->next=q1.front();            }            i++;        }    }};
0 0
原创粉丝点击