题目链接:Populating Next Right Pointers in Each Node
题目内容:
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:
1 -> NULL / 2 -> 3 -> NULL / / 4->5->6->7 -> NULL
题目解法:
这道题本来只是一道简单的计层BFS题目,但是有一个对于常数额外空间复杂度的要求,因此不能使用传统的队列BFS,可以只定义一个变量cur,根据树的性质来完成BFS,具体方法如下:
首先初始化cur为root,cur的每次动作是从左到右的,通过cur = cur->next实现;当cur->next==NULL时,让cur沿着root的左子树往下走,也就是root = root->left; cur = root;当我们设置next时,实际上我们是设置的下一层的next,因此当访问当前层的next时,已经被设置过。
下面举个例子,如上面一棵完全二叉树,假设现在cur=2,在第一层我们已经设置了2的next为3,因此在本层通过cur->left->next=cur->right设置4->5,因为cur->next!=NULL,因此我们设置cur->right->next=cur->next->left,也就是2的右子树5指向3的左子树6,然后cur=3,继续操作。
代码如下:
/** * 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; TreeLinkNode *cur; while(root->left != NULL){ 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; } } };