/*由于二叉树的层序遍历空间是O(n),可以利用建立的链表进行遍历。
参考自:https://github.com/soulmachine/leetcode*/
class Solution {
public:
void connect(TreeLinkNode *root) {
while(root != nullptr){
TreeLinkNode *pre(nullptr), *next(nullptr);
for(; root != nullptr; root = root->next){
if(next == nullptr) next = root->left != nullptr ? root->left : root->right;
if(root->left != nullptr){
if(pre != nullptr) pre->next = root->left;
pre = root->left;
}
if(root->right != nullptr){
if(pre != nullptr) pre->next = root->right;
pre = root->right;
}
}
root = next;
}
}
};
LeetCode之Populating Next Right Pointers in Each Node II
最新推荐文章于 2021-09-24 12:05:40 发布