题目:
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:
扫描二维码关注公众号,回复:
5871325 查看本文章
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL思路:题目中说明 You may only use constant extra space. 所以不能使用递归啦~改用指针&双重循环
1.从最右节点开始走(图中1,2,4)
2.如果当前节点是上个节点的左节点,那么其next是上个节点的右节点
3.如果当前节点是三个节点的右节点,那么其next是上个结点的next的左节点。
4.循环中注意判断是否为空。
/**
* 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==NULL)
return;
while(root->left!=NULL){
TreeLinkNode* cur = root;
while(cur!=NULL){
cur->left->next = cur->right;
if(cur->next!=NULL){
cur->right->next = cur->next->left;
}
cur = cur->next;
}
root = root->left;
}
}
};