您的位置:首页 > Web前端 > Node.js

116. Populating Next Right Pointers in Each Node

2017-07-10 20:24 357 查看
题目

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;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: