Leetcode在线编程 populating-next-right-pointers-in-each-node
题目链接
populating-next-right-pointers-in-each-node
题目描述
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
题意
简单点就是,给定完全二叉树,将它每一层的顶点串起来
解题思路
我采用的是非递归去层次遍历完全二叉树
设置一个队列q保存当前层的顶点
设置一个动态数组v保存下一层的顶点
具体操作:
队列q中pop出结点tmp
1)就将tmp的左右节点,保存在v中,等待下次遍历,这样就可以保证队列q是同一层的顶点
2)tmp接到链表尾部pre->next,同时将pre =tmp ,就将同一层的顶点串起来了
AC代码
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==NULL)
return ;
queue<TreeLinkNode*>q;
q.push(root);
while(!q.empty())
{
TreeLinkNode* pre =NULL;
vector<TreeLinkNode*>v;
while(!q.empty())
{
TreeLinkNode *tmp1 = q.front();
q.pop();
if(pre==NULL)
{
tmp1->next = NULL;
pre = tmp1;
}
else
{
pre ->next = tmp1;
pre = tmp1;
pre->next =NULL;
}
if(tmp1->left)
v.push_back(tmp1->left);
if(tmp1->right)
v.push_back(tmp1->right);
}
for(int i = 0 ; i < v.size() ; i++)
{
q.push(v[i]);
}
}
}
};
本文提供了一种使用非递归层次遍历的方法来解决LeetCode上的一道题——“填充每个节点的下一个右侧节点指针”。通过使用队列保存当前层节点并设置动态数组保存下一层节点的方式,实现对完全二叉树中同一层节点的连接。
272

被折叠的 条评论
为什么被折叠?



