populating-next-right-pointers-in-each-node
来源:互联网 发布:重装系统无法安装软件 编辑:程序博客网 时间:2024/06/06 19:58
题目:
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 toNULL.
Initially, all next pointers are set toNULL.
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
程序:
层序遍历的应用
class Solution {public: void connect(TreeLinkNode *root) { if (root == NULL) return; queue<TreeLinkNode*> q; q.push(root); while (!q.empty()) { vector<TreeLinkNode*> v; while (!q.empty()) { v.push_back(q.front()); q.pop(); } if (v.size() == 0) break; for (int i = 0; i<v.size() - 1; i++) { if (v[i]->left) q.push(v[i]->left); if (v[i]->right) q.push(v[i]->right); v[i]->next = v[i + 1]; } if (v[v.size() - 1]->left) q.push(v[v.size() - 1]->left); if (v[v.size() - 1]->right) q.push(v[v.size() - 1]->right); v[v.size() - 1]->next = NULL; } }};
- 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
- 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
- 继承
- Android Studio 插件开发详解一:入门练手
- MATLAB对三阶魔方建模并进行旋转操作
- 一条指令分条件向多个表插入数据
- html input文本输入框的一些总结
- populating-next-right-pointers-in-each-node
- 用TensorFlow和TensorBoard从零开始构建ConvNet(CNN)
- spi驱动框架全面分析,从master驱动到设备驱动
- Azure 中 Linux 虚拟机的大小
- js闭包函数与JQuery插件模板
- 栈和队列的相互转换替代
- MyBatis注解开发-@Insert和@InsertProvider
- hibernate node to traverse cannot be null!
- RabbitMQ镜像队列实现原理