参考链接
http://blog.youkuaiyun.com/beiyetengqing/article/details/8454924
题目描述
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 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
题目分析
给了一个完全二叉树,把所有在同一层的结点的next指针指向右侧结点
思路一:使用队列进行广度例行遍历。需要注意一个技巧就是如果记录一层结束,如代码里的levelSum的变化
思路二:使用递归。需要注意的技巧就是灵活使用已经求行的next指针,从左子树指向右子树。
这种方法只适用于完整二叉树。
代码示例
#include
#include
using namespace std;
#define DEBUG
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
// 队列 广度遍历
#if 0
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root == NULL) return;
queue
treeque;
treeque.push(root);
int levelSum = treeque.size();
while(!treeque.empty())
{
TreeLinkNode *front = treeque.front();
treeque.pop();
if(front->left != NULL) treeque.push(front->left);
if(front->right != NULL) treeque.push(front->right);
levelSum--;
if(levelSum == 0)
{
front->next=NULL;
levelSum = treeque.size();
#ifdef DEBUG
printf("%d next=NULL\n",front->val);
#endif
}
else
{
front->next = treeque.front();
#ifdef DEBUG
printf("%d next=%d\n",front->val,treeque.front()->val);
#endif
}
}
}
};
#elif 1
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root == NULL) return;
if(root->left != NULL)
root->left->next = root->right/*,printf("%d next=%d\n",root->left->val,root->right->val)*/;
if(root->right != NULL && root->next != NULL)//充分利用已经有的next指针
root->right->next = root->next->left/*,printf("%d next=%d\n",root->right->val,root->next->left->val)*/;
connect(root->left);
connect(root->right);
}
};
#endif
void test0()
{
TreeLinkNode node1(1);
TreeLinkNode node2(2);
TreeLinkNode node3(3);
TreeLinkNode node4(4);
TreeLinkNode node5(5);
TreeLinkNode node6(6);
TreeLinkNode node7(7);
node1.left = &node2;
node1.right = &node3;
node2.left = &node4;
node2.right = &node5;
node3.left = &node6;
node3.right = &node7;
Solution so;
so.connect(&node1);
}
int main()
{
test0();
return 0;
}
推荐学习C++的资料
C++标准函数库
在线C++API查询
本文介绍了一种算法,用于填充完全二叉树中每个节点的next指针,使其指向同一层的下一个节点。提供了两种实现方法:一种是使用队列进行广度优先搜索,另一种是采用递归方式利用已填充的next指针。

410

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



