题目描述:
给定一个二叉树
struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *next; }
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL
。
初始状态下,所有 next 指针都被设置为 NULL
。
说明:
- 你只能使用额外常数空间。
- 使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
示例:
给定二叉树,
1 / \ 2 3 / \ \ 4 5 7
调用你的函数后,该二叉树变为:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
解题思路:
首先如果使用队列进行层次遍历,将会很简单,但是题目要求使用额外常数空间,使用队列就不行了。(想了好久,自己写的程序总会有一些bug,并且逻辑都比较复杂。看了一下网上代码,觉得自己还是去工地搬砖的好。)
首先申请了一个节点temp作为记录节点,创建left指针指向temp,然后进入循环进行层次遍历;
如果当前节点有左儿子,将left->next指向root->left(这里如果是每层的第一次操作,temp->next将指向root->left,因为初始位置left是指向temp的),其他的就好理解了,如果有右儿子,同样的操作。
如果最后root->next==nullptr,说明这个一层已经遍历完成,将root=temp->next,就到了下一层首节点。然后temp->next=nullptr,防止死循环。
代码:
/**
* 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) {
TreeLinkNode *temp=new TreeLinkNode(0),*left=temp;
while(root){
if(root->left){
left->next=root->left;
left=root->left;
}
if(root->right){
left->next=root->right;
left=root->right;
}
root=root->next;
if(!root){
left=temp;
root=temp->next;
temp->next=nullptr;
}
}
}
};