本文主要是介绍LeetCode之Populating Next Right Pointers in Each Node II,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*由于二叉树的层序遍历空间是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的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!