leetcode:Populating Next Right Pointers in Each Node

来源:互联网 发布:日韩护肤品推荐 知乎 编辑:程序博客网 时间:2024/06/06 06:23
/** * https://leetcode.com/problems/populating-next-right-pointers-in-each-node/#/description * */#include<iostream>#include<vector>#include<stack>using namespace std;using vecIter = std::vector<int>::iterator;struct TreeLinkNode {     int val;    TreeLinkNode *left, *right, *next;    TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}};class Solution{public:     Solution(){};    ~ Solution(){};    void connect(TreeLinkNode* root){        if(NULL==root) return;        TreeLinkNode* curLev;        while(root->left!=NULL){            curLev=root;            while(curLev!=NULL){                curLev->left->next=curLev->right;                if(curLev->next!=NULL)                    curLev->right->next=curLev->next->left;                curLev=curLev->next;            }            root=root->left;        }    }};// Test Unit////          1//         / \//        2   3//       /\   /\//      4 5  6  7//     /\ /\ /\ /\//    8 9A BC DE F// ( A == 10 ...)TreeLinkNode* createBinaryTree(vecIter beg,vecIter end){    vector<TreeLinkNode*> vec;    //把vector数组的int型内容,转化为树结构类型,存到vec数组当中    for(vecIter it=beg;it!=end;++it)                    vec.push_back(new TreeLinkNode(*it));    //把vec数组中的结果组织成树的形式    for(int i=0,pos=0;pos!=vec.size()-1;++i)    {        vec[i]->left=vec[++pos];        vec[i]->right=vec[++pos];    }    //返回起始地址    return *vec.begin();}//输出节点的内容void print(TreeLinkNode* root){    while(root)    {        cout<<root->val;        TreeLinkNode* cur=root->next;        while(cur)        {            cout<<"->"<<cur->val;            cur=cur->next;        }        cout<<endl;        root=root->left;    }}int main(int argc,char** argv){    vector<int> vec={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};    TreeLinkNode* root=createBinaryTree(vec.begin(),vec.end());    Solution s;    s.connect(root);    print(root);    return 0;}
阅读全文
0 0
原创粉丝点击