LeetCode116—Populating Next Right Pointers in Each Node
来源:互联网 发布:沙耶之歌 知乎 编辑:程序博客网 时间:2024/06/05 06:07
LeetCode116—Populating Next Right Pointers in Each Node
原题
Given a binary tree
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next;}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4 ->5 ->6 -> 7 -> NULL
分析
就是把完全二叉树的连起来,因为题目数据结构中给了next指针,按照示例输出不难得出就是把完全二叉树从左到右“串”起来,最后一个节点指向NULL。
题目的Hint的给的提示深度优先搜索(我还没想到dfs的解法),但是这题用层序遍历(BFS)会比较简单,包括下一题LeetCode117—Populating Next Right Pointers in Each Node II 针对非完全二叉树的情形,也可以用相同的方法,事实上两者我用的同一份代码。
class Solution {private: void bfs(TreeLinkNode *root)//层序遍历 { if (root == NULL) return; vector<TreeLinkNode*>temp; vector<TreeLinkNode*>q; int front = 0; int rear = 1; q.push_back(root); while (front < q.size()) { rear = q.size(); while (front < rear) { temp.push_back(q[front]); if (q[front]->left != NULL) q.push_back(q[front]->left); if (q[front]->right != NULL) q.push_back(q[front]->right); ++front; } int i; for ( i = 0; i < temp.size()-1; i++) { temp[i]->next = temp[i + 1]; } temp[i]->next = NULL; temp.clear();//结束一层 } }public: void connect(TreeLinkNode *root) { bfs(root); }};
- LeetCode116—Populating Next Right Pointers in Each Node
- LeetCode116 Populating Next Right Pointers in Each Node
- leetcode116~Populating Next Right Pointers in Each Node
- LeetCode116 Populating Next Right Pointers in Each Node
- leetcode116. Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- 图形界面系统XFree86的历史
- 顺序表的实现
- asp微信公众号自动回复开发案列之新闻查询机器人
- 第40讲项目2——水仙花数(版本1)
- QML 中的 console 对象
- LeetCode116—Populating Next Right Pointers in Each Node
- 如何巧妙的使用sshpass来提高效率
- 3.javascript函数
- 哈夫曼树
- java集合中各个接口与实现类的区别
- JAVA String 类 总结(1)
- 求数组逆序对个数
- Codeforces 630H Benches
- poj3524 Corn Fields(状态压缩dp)