LeetCode116—Populating Next Right Pointers in Each Node
2016-04-09 20:44
661 查看
LeetCode116—Populating Next Right Pointers in Each Node
原题
Given a binary treestruct 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); } };
相关文章推荐
- leetcode 222. Count Complete Tree Nodes
- 点击链接更换图片和相应文本 childNotes nodeType nodeValue
- node入门(二)——gulpfile.js初探
- leetcode- Delete Node in a Linked List&Remove Linked List Elements
- 关于node.js资料集
- 如何在Ubuntu上安装最新版本的Node.js
- node初探(很全的hello world工程)
- 磁盘被占满 系统出现 no space left on 报错(block被占满/inode被占满)
- 24. Swap Nodes in Pairs | Java最短代码实现
- nodejs+Ajax访问路由,返回json数据
- mongoose的在node中的使用。入门
- Node.js介绍
- Node.js-2.模块
- leetcode: 237. Delete Node in a Linked List
- FILE、inode、fork和vfork
- Node.js中,获取req请求的原始IP
- 浅谈inode
- 一个Java码农的Node之旅
- SpriteKit-(SKNode)
- nodemailer实现node发送邮件