Populating Next Right Pointers in Each Node I & II
来源:互联网 发布:蚂蚁分类信息系统 源码 编辑:程序博客网 时间:2024/05/13 23:58
由于这个题目的I是II的子集(I是II的一种特殊情况),所以II能通过的代码I肯定也可以通过。
咋一看题目没想太多,直接想到用两个队列,一个放当前层的节点,另一个放当前层节点的子节点(下一层),然后循环给每层节点的next赋值。
class Solution {private: bool checkend(queue <TreeLinkNode*> que){ while(!que.empty()){ if(que.front()->left || que.front()->right) return true; que.pop(); } return false; }public: void connect(TreeLinkNode *root) { queue <TreeLinkNode*> parent; queue <TreeLinkNode*> child; if(!root) return; parent.push(root); while(checkend(parent)){ while(!parent.empty()){ if(parent.front()->left) child.push(parent.front()->left); if(parent.front()->right) child.push(parent.front()->right); parent.pop(); } while(!child.empty()){ parent.push(child.front()); child.pop(); if(!child.empty()) parent.back()->next=child.front(); } } }};
然后看到了题目有一段You may only use constant extra space。。。
呵呵,那就是不能用队列了咯。。。网上参考了[1],发现一个更直接的方法,就是小于等于当前结点层的结点next都已经处理完毕,然后只需递归调用右孩子和左孩子(顺序不能倒过来!暂时没想明白为什么)。
class Solution {public: void connect(TreeLinkNode *root) { if (root == NULL) { return; } TreeLinkNode* p = root->next; while (p != NULL) { if (p->left != NULL) { p = p->left; break; } if (p->right != NULL) { p = p->right; break; } p = p->next; } if (root->right != NULL) { root->right->next = p; } if (root->left != NULL) { root->left->next = root->right == NULL ? p : root->right; } connect(root->right); connect(root->left); }};
以上两种方法在II运行时间一样,在I中第二种方法比第一种长一倍时间。
参考:
[1] http://blog.csdn.net/wzy_1988/article/details/17412025
0 0
- Populating Next Right Pointers in Each Node (I & II)
- 【LeetCode】Populating Next Right Pointers in Each Node I & II
- Populating Next Right Pointers in Each Node I&II
- Populating Next Right Pointers in Each Node I & II
- LeetCode:Populating Next Right Pointers in Each Node I & II
- Populating Next Right Pointers in Each Node I & II
- [LeetCode] Populating Next Right Pointers in Each Node I &II
- LeetCode:Populating Next Right Pointers in Each Node I&II
- [Leetcode]Populating Next Right Pointers in Each Node I && II
- LeetCode - Populating Next Right Pointers in Each Node I && II
- Populating Next Right Pointers in Each Node I, II
- 【leetcode】Populating Next Right Pointers in Each Node I&&II
- [LeetCode] Populating Next Right Pointers in Each Node I, II
- Populating Next Right Pointers in Each Node I, II
- 116. Populating Next Right Pointers in Each Node I&II
- [LeetCode]Populating Next Right Pointers in Each Node I & II
- Populating Next Right Pointers in Each Node I, II
- Populating Next Right Pointers in Each Node I, II
- 将visual studio 中的解决方案整体移植给别人
- typedef的用途
- Java Class类学习
- 漫谈C++内存分配失败
- Android APK 反编译图文详解
- Populating Next Right Pointers in Each Node I & II
- 台湾男子被控性侵 同父母牵百公斤活猪登门道歉
- 单反相机里的照片误删了怎么恢复
- 二叉树各种遍历方式实现
- 如何查看gpio 使用状态,以及被那些模块request
- http post提交数据
- Java日期操作
- Android平台下的JNI开发
- log4j 详细配置