117.每个节点的右向指针之二 C++实现LeetCode( 二 )
这里再来说下 dummy 结点是怎样指向每层的首结点的前一个结点的 , 过程是这样的 , dummy 是创建出来的一个新的结点 , 其目的是为了指向 root 结点的下一层的首结点的前一个 , 具体是这么做到的呢 , 主要是靠 cur 指针 , 首先 cur 指向 dummy , 然后 cur 再连上 root 下一层的首结点 , 这样 dummy 也就连上了 。然后当 root 层遍历完了之后 , root 需要往下移动一层 , 这样 dummy 结点之后连接的位置就正好赋值给 root , 然后 cur 再指向 dummy , dummy 之后断开 , 这样又回到了初始状态 , 以此往复就可以都连上了 , 代码如下:
解法三:
class Solution {public:Node* connect(Node* root) {Node *dummy = new Node(-1), *cur = dummy, *head = root;while (root) {if (root->left) {cur->next = root->left;cur = cur->next;}if (root->right) {cur->next = root->right;cur = cur->next;}root = root->next;if (!root) {cur = dummy;root = dummy->next;dummy->next = NULL;}}return head;}};
类似题目:
Populating Next Right Pointers in Each Node
参考资料:
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/37813/java-solution-with-constant-space
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/37828/o1-space-on-complexity-iterative-solution
到此这篇关于C++实现LeetCode(117.每个节点的右向指针之二)的文章就介绍到这了,更多相关C++实现每个节点的右向指针之二内容请搜索趣讯吧以前的文章或继续浏览下面的相关文章希望大家以后多多支持趣讯吧!
