https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:
struct Node {
int val;
Node *left;
Node *right;
Node *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.
Follow up:
- You may only use constant extra space.
- Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.
Example 1:

Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#] Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.
Constraints:
- The number of nodes in the given tree is less than
4096. -1000 <= node.val <= 1000
算法思路:
最简单,也是最容易想到的就模拟levelOrder遍历过程,然后不断的加上next right pointer,实际上本题是一个完美二叉树,前序遍历,中序遍历,后续遍历理论上都可完成上述操作。
//模拟层序遍历过程加上next right pointer
//O(n) O(n)
class Solution {
public:
Node* connect(Node* root) {
if(root == NULL) return NULL;
queue<Node*> que;
que.push(root);
Node* node = NULL;
while(!que.empty()){
int n = que.size();
for(int i = 0; i < n; i++){
if(i == 0){
node = que.front();
que.pop();
}else{
node->next = que.front();
que.pop();
node = node->next;
}
if(node->left){
que.push(node->left);
}
if(node->right){
que.push(node->right);
}
}
}
return root;
}
};
题目follow up中说使用O(1)空间复杂度,递归开销不计入空间开销,这就引导我们在模拟递归过程中加上next right pointer,考虑到是完美二叉树,这里模拟前序遍历过程加上next right pointer,代码非常简洁。
//O(n) O(1)
class Solution {
public:
Node* connect(Node* root) {
if(!root || !root->right) return root;
root->left->next = root->right;
if(root->next) root->right->next = root->next->left;
connect(root->left);
connect(root->right);
return root;
}
};
585

被折叠的 条评论
为什么被折叠?



