116. Populating Next Right Pointers in Each Node
来源:互联网 发布:ubuntu 网卡重启不生效 编辑:程序博客网 时间:2024/06/03 18:56
题目
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分析
层次遍历完全二叉树,用两个deque保存节点,当前队列为flag所指向队列,队首元素出队后根据是否有左子节点判断是否为最下层,如果不是则在1-flag中保存其左右子节点,然后根据flag队列是否为空决定当前元素的next指向,如果当前队列为空的转换flag值指向下一层的队列,由于最后一层不会向下一层队列压入任何节点,所以while循环能够在全部遍历后退出。
/** * 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 ; vector< deque<TreeLinkNode*> > v(2); int flag=0; v[0].push_back(root); while(!v[flag].empty()){ TreeLinkNode* t=v[flag].front(); v[flag].pop_front(); if(t->left!=NULL){ v[1-flag].push_back(t->left); v[1-flag].push_back(t->right); } if(!v[flag].empty()) t->next=v[flag].front(); else flag=1-flag; } }};
阅读全文
0 0
- 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
- C++中的类模板详细讲述
- bs4简单示例
- java中堆内存(heap)和栈内存(stack)区别
- PHP中使用for循环来遍历下标连续的二维索引数组
- 继承实现业绩、成绩评判
- 116. Populating Next Right Pointers in Each Node
- Java 接口(interface)的用途和好处
- POJ 2481__Cows
- 环境配置
- Java编程思想之控制流程
- 倒水问题(Fill,UVa 10603)
- 如何查看mysql的端口号
- r语言聚类分析
- 编程题——复杂链表的复制