117. Populating Next Right Pointers in Each Node II
来源:互联网 发布:数据质量评估 编辑:程序博客网 时间:2024/05/16 07:25
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space. For example, Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
不同于上一题,这题的二叉树并不是完全二叉树,我们不光需要提供first指针用来表示一层的第一个元素,同时也需要使用另一个lst指针表示该层上一次遍历的元素。那么我们只需要处理好如何设置last的next指针就可以了。
代码如下:
class Solution {public: void connect(TreeLinkNode *root) { if(!root) { return; } TreeLinkNode* p = root; TreeLinkNode* first = NULL; TreeLinkNode* last = NULL; while(p) { //设置下层第一个元素 if(!first) { if(p->left) { first = p->left; } else if(p->right) { first = p->right; } } if(p->left) { //如果有last,则设置last的next if(last) { last->next = p->left; } //last为left last = p->left; } if(p->right) { //如果有last,则设置last的next if(last) { last->next = p->right; } //last为right last = p->right; } //如果有next,则转到next if(p->next) { p = p->next; } else { //转到下一层 p = first; last = NULL; first = NULL; } } }};
9.14
------------
这道题的关键之处就在于想清楚最后两层。!!!!!!
0 0
- LeetCode 117. Populating Next Right Pointers in Each Node II
- [LeetCode]117.Populating Next Right Pointers in Each Node II
- [Leetcode] 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- [leetcode] 117.Populating Next Right Pointers in Each Node II
- 116. Populating Next Right Pointers in Each Node && 117. II
- [LeetCode]117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- [leetcode]117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- LeetCode 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- Leetcode 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- [LeetCode] 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 117. Populating Next Right Pointers in Each Node II
- 14 个 Linux grep 命令的例子
- 音频文件播放之音量控制【海思平台】
- 页面弹层置灰 js
- 黑马程序员---------------------java基础--------------------网络编程
- fatal:pathspec did not match any file
- 117. Populating Next Right Pointers in Each Node II
- iOS给Model排序
- Android使用XUtils框架上传照片(一张或多张)和文本,服务器接收照片和文字(无乱码)
- URL编码与两次encodeURI
- 为什么有些人用一年时间获得了你十年的工作经验?
- I学霸官方免费教程二十八:Java排序算法之选择排序和冒泡排序
- 最长回文子串
- poj -2513-Colored Sticks-哈希&并查集或者字典树&并查集
- 单元最短路问题