题目描述:
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.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
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
将二叉树每一层都从左到右链接起来,而且只能使用常数空间。
递归的解法较为简单一点,对于当前递归的节点,将左节点指向右节点,将右节点指向根节点指向节点的左节点。
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==NULL) return;
if(root->left!=NULL)
{
root->left->next=root->right;
if(root->next!=NULL) root->right->next=root->next->left;
}
connect(root->left);
connect(root->right);
}
};
迭代的解法要复杂一些,对每一层依次连接,但是需要在遍历每一层之前存储该层的起点,从而在遍历完一层之后,可以继续遍历下一层。
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==NULL) return;
TreeLinkNode* start=root;
while(start->left!=NULL)
{
TreeLinkNode* cur=start;
while(cur!=NULL)
{
cur->left->next=cur->right;
if(cur->next!=NULL) cur->right->next=cur->next->left;
cur=cur->next;
}
start=start->left;
}
return;
}
};