LeetCode Problem: Populating Next Right Pointers in Each Node, Level traversal of binary tree

By | 2012 年 12 月 24 日

It’s easy to doing this by using a queue, doing a level traversal of binary tree.

Populating Next Right Pointers in Each Node
Given a binary tree
}
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
```

Code, 160ms pass the large test set.

```/**
* Definition for binary tree with next pointer.
*  int val;
*  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
// Start typing your C/C++ solution below
// DO NOT write int main() function
queue q;
if(root) {
q.push(root);
q.push(NULL);
}
while(q.size()) {
q.pop();
if(cur) {
cur->next = q.front();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
} else {
if (q.size()) q.push(NULL);
}
}
}
};
```

Code rewrite at 2013-1-19, more simple

```class Solution {
public:
queue q;
q.push(root);
q.push(NULL);
while(true) {
q.pop();
if(cur) {
cur->next = q.front();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
} else {
if (q.size() == 0 || q.front() == NULL) return;
q.push(NULL);
}
}
}
};
```

13 thoughts on “LeetCode Problem: Populating Next Right Pointers in Each Node, Level traversal of binary tree”

1. qyu

为什么不用递归呢，不需要额外分配空间：
class Solution {
public:
if (root != NULL && root->left != NULL) root->left->next = root->right;
if (root != NULL && root->next != NULL && root->next->left != NULL) root->right->next = root->next->left;
if (root != NULL && root->left != NULL) connect(root->left);
if (root != NULL && root->right != NULL) connect(root->right);
}
};

2. sangoblin
```class Solution {
public:
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (!root || !root->left)  return;

auto parent = root, son = root->left;

while (son)
{
auto back = son;

while (son)
{
son->next = parent->right;
son = son->next;
parent = parent->next;
son->next = parent?parent->left:nullptr;
son = son->next;
}

parent = back;
son = parent->left;
}
}
};
```

因为我们在遍历下一层时，上一层已经连接好，所以可以在常量memory的条件下遍历

3. A*

这是用dfs解得，另一种思路，感觉更思路清晰：
// Start typing your Java solution below
// DO NOT write main() function

if(root==null || root.left==null || root.right==null){
return;
}

root.left.next = root.right;
if(root.next != null){
root.right.next = root.next.left;
}
else{
root.right.next = null;
}

connect(root.left);
connect(root.right);
}