117. Populating Next Right Pointers in Each Node II
by Botao Xiao
Question
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.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
Example:
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
Thinking:
- Method 1:BFS
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
LinkedList<TreeLinkNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
int len = queue.size();
TreeLinkNode pre = null;
for(int i = 0; i < len; i++){
TreeLinkNode temp = queue.poll();
if(temp.left != null) queue.add(temp.left);
if(temp.right != null) queue.add(temp.right);
if(pre != null){
pre.next = temp;
}
pre = temp;
}
pre.next = null;
}
}
}
二刷
没看出来和上一道题有什么区别。
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root == null) return;
LinkedList<TreeLinkNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
TreeLinkNode pre = null;
TreeLinkNode next = null;
for(int i = 0; i < size; i++){
pre = q.poll();
next = i == size - 1 ? null: q.peek();
if(pre.left != null) q.offer(pre.left);
if(pre.right != null) q.offer(pre.right);
pre.next = next;
}
}
}
}
Subscribe via RSS