[Leetcode] Populating Next Right Pointers in Each Node

来源:互联网 发布:乡镇网络维护员工资 编辑:程序博客网 时间:2024/04/27 21:51
/** * 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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if (!root) return;                if (!root->left || !root->right)            return;                    TreeLinkNode* next = NULL;        TreeLinkNode* p = root;                while (p)        {            if (p->next)                next = p->next->left;            else                next = NULL;                        p->left->next = p->right;            p->right->next = next;            p = p->next;        }        connect(root->left);    }};

原创粉丝点击