Populating Next Right Pointers in Each Node(leetcode)
来源:互联网 发布:海康网络监控摄像头 编辑:程序博客网 时间:2024/06/06 05:31
题目:
Follow up for problem "Populating Next Right Pointers in Each Node".
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
题目来源:这两个题目是一样的
https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
解题思路:层次遍历
#include<iostream>#include<queue>using namespace std;struct TreeLinkNode {int val;TreeLinkNode *left, *right, *next;TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}};void connect(TreeLinkNode *root) {if(root==NULL)return ;queue<TreeLinkNode *> q;q.push(root);int k=0,level=1;while(!q.empty()){k=level;level=0;for(int i=0;i<k;i++){TreeLinkNode *temp=q.front();q.pop();if(temp->left!=NULL){q.push(temp->left);level++;}if(temp->right!=NULL){q.push(temp->right);level++;}if(i!=k-1)temp->next=q.front();elsetemp->next=NULL;}}}int main(){TreeLinkNode *root=new TreeLinkNode(1);root->left=new TreeLinkNode(2);root->right=new TreeLinkNode(3);root->left->left=new TreeLinkNode(4);root->left->right=new TreeLinkNode(5);root->right->right=new TreeLinkNode(6);system("pause");return 0;}
0 0
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- leetcode Populating Next Right Pointers in Each Node &&Populating Next Right Pointers in Each Node||
- LeetCode Populating Next Right Pointers in Each Node & Populating Next Right Pointers in Each Node I
- 【Leetcode】Populating Next Right Pointers in Each Node in JAVA
- LeetCode Populating Next Right Pointers in Each Node
- LeetCode Populating Next Right Pointers in Each Node II
- [Leetcode] Populating Next Right Pointers in Each Node
- LeetCode: Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node
- [LeetCode] Populating Next Right Pointers in Each Node II
- 【leetcode】 Populating Next Right Pointers in Each Node
- leetcode 78: Populating Next Right Pointers in Each Node
- leetcode 79: Populating Next Right Pointers in Each Node II
- Leetcode: Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node ii
- leetcode Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node
- Scala安装
- 位运算:左移右移及原码补码转换
- Spark导出
- 《移动设计》阅读笔记
- java 中的序列化
- Populating Next Right Pointers in Each Node(leetcode)
- 给Linux初学者和管理员一个终极命令行"备忘单"
- JS获取字符串实际长度!
- Spark 4
- Spark--5
- 支持取消操作和暂停操作的Backgroundworker示例一则
- 弹出UIDateicker
- Ubunt 14.04 lts 安装 workbench及相关错误解决
- 冯永昌:云计算与大数据时代的量化投资