Populating Next Right Pointers in Each Node I
题目描述
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,
After calling your function, the tree should look like:
题目要求给出完全二叉树每个结点的next指针所指向的值。
解题思路
本题给定了限定条件,每棵树均为完全二叉树,对一个结点L而言其子树的结点的next指针分两种情况:
- 左子结点:L的右子节点(L->right);
- 右子节点:L的next结点的左子结点(L->next->left),如果L本身为NULL,则该结点的next指针也指向NULL。
再对L的左右子结点递归进行处理,则可处理整棵树。
/**
* 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) return;
TreeLinkNode* left = root->left;
TreeLinkNode* right = root->right;
if(left) left->next = right;
if(right)
{
if(root->next)
right->next = root->next->left;
else
right->next = NULL;
}
connect(root->left);
connect(root->right);
}
};
Populating Next Right Pointers in Each Node II
题目描述
Follow up for problem “Populating Next Right Pointers in Each Node”.
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
After calling your function, the tree should look like:
与第一题不同的是,本题求的是普通二叉树的next指针。(第一题是完全二叉树)
解题思路
从第二题和第一题的区别可以看出,第二题不能保证每个结点的存在,所以对于当前结点L
1 左子节点:
1.1 L->right存在,则next = L->right;
1.2 L->right不存在,next = L->next->left;(循环查找知道L->next != NULL位置,若L->next ->left不存在则为L->next->right);
2 右子节点与1.2的情况相同;
/**
* 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 findNext(TreeLinkNode* p, TreeLinkNode* node)
{
if( !node ) return;
while(node)
{
if(node->left)
{
p->next = node->left;
break;
}
else if(node->right)
{
p->next = node->right;
break;
}
node = node->next;
}
}
void connect(TreeLinkNode *root) {
if(!root) return;
TreeLinkNode* left = root->left;
TreeLinkNode* right = root->right;
if(left)
{
if(right) left->next = right;
else findNext(left, root->next);
}
if(right) findNext(right, root->next);
connect(right);
connect(left);
}
};