OJ-Populating Next Right Pointers in Each Node
来源:互联网 发布:武汉 知乎 编辑:程序博客网 时间:2024/06/07 01:05
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
//p保存头节点,每次循环2^h次,使p->next = p;
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */
class Solution {public: void connect(TreeLinkNode *root) { if(root==NULL) return; deque<TreeLinkNode*> s; TreeLinkNode *p = root; TreeLinkNode *q = NULL; s.push_back(p); int h=1; while(p!=NULL) { for(int i = 0;i<h-1;i++) { s.pop_front(); q = s.front(); p->next = q; if(p->left != NULL) { s.push_back(p->left); s.push_back(p->right); } p = p->next; } s.pop_front(); p->next == NULL; if(p->left != NULL) { s.push_back(p->left); s.push_back(p->right); } if(!s.empty()) { p = s.front(); } else { p == NULL; break; } h = 2*h; } }};
0 0
- 【LeetCode OJ】Populating Next Right Pointers in Each Node II
- LeetCode OJ:Populating Next Right Pointers in Each Node
- LeetCode OJ:Populating Next Right Pointers in Each Node II
- OJ-Populating Next Right Pointers in Each Node
- LeetCode OJ - Populating Next Right Pointers in Each Node II
- [LeetCode OJ]Populating Next Right Pointers in Each Node
- LeetCode OJ Populating Next Right Pointers in Each Node II
- LeetCode OJ 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 使用viewpager 做滚图广告
- ubuntu 下安装maven+eclipse环境
- Error:Initialize scatter file failed.Please check the scatter file name you load is legal
- Android开发之Service与Activity数据交互(源代码分享)
- QT 的信号与槽机制介绍
- OJ-Populating Next Right Pointers in Each Node
- 郝斌数据结构(五):树
- linux下IPTABLES配置详解
- Android线程中handler的使用
- 用js设置下拉框为只读
- bluetooth开发(二)------基于rfcomm通信编程之服务器端
- 矩阵的本质理解
- 鼠标左键单击双击冲突的一种解决方法
- CodeIgniter通过hook的方式实现简单的权限控制