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

LeetCode OJ 之 Populating Next Right Pointers in Each Node (为每个结点填充右指针)

2014-12-07 19:06 751 查看

题目:

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
.

为每个结点填充next指针指向它的下一个右结点。如果没有右结点,next指针置为空。next指针初始值都为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

思路:

核心思想是BFS,具体分析请看代码。

迭代版:

/**
* 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:
//由题知,满二叉树一个结点的左右孩子同时存在或者不存在
//可用BFS按层遍历,如果当前层的next已经设置好,那么下一层的可以这样设置
//root->left->next = root->right ,root->right->next = root->next->left(if(cur->next != NULL))
void connect(TreeLinkNode *root)
{
if(root == NULL)
return ;
TreeLinkNode *cur ;
//下面循环内的操作都是对root的下一行操作,所以判断条件是root->left != NULL,第一行root的next也不需要设置,因初始为NULL
//如果root是最后一行,则这一行的next不需要再设置,因为已经初始化为NULL了
while(root->left != NULL)
{
cur = root;
//每个while循环从当前层出发,处理下一层结点的next
while(cur != NULL)
{
cur->left->next = cur->right;
if(cur->next != NULL)
cur->right->next = cur->next->left;
cur = cur->next;//本层结点向后移动
}
root = root->left;//向下一层移动
}
}
};

递归版:

/**
* 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:
//由题知,满二叉树一个结点的左右孩子同时存在或者不存在
//可用BFS按层遍历,如果当前层的next已经设置好,那么下一层的可以这样设置
//root->left->next = root->right ,root->right->next = root->next->left(if(cur->next != NULL))
void connect(TreeLinkNode *root)
{
//递归结束条件,如果root为空,或者root为最后一层,则直接返回,不需要设置
if(root == NULL || root->left == NULL)
return ;
//对当前结点孩子结点进行设置
if(root->left != NULL)
{
root->left->next = root->right;
if(root->next != NULL)
root->right->next = root->next->left;//如果root存在next,则设置root的右孩子的next,否则就为空
}
//对下一层结点递归处理
connect(root->left);
connect(root->right);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode
相关文章推荐