LeetCode 116. 【Java】116. Populating Next Right Pointers in Each Node
原题链接
中等
作者:
tt2767
,
2020-03-25 16:09:01
,
所有人可见
,
阅读 511
/**
1. bfs 按层,从左到右遍历,并为其加入指针
2. 处理当前层时, 我们可以认为上一层的平行指针已经建立完了, 可以直接遍历一层
*/
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if (root == null || (root.left == null && root.right == null)) return root;
return bfsWithSelf(root);
// return bfsWithQueue(root);
}
public Node bfsWithSelf(Node root){
for (Node p = root; p.left != null ; p = p.left){
for (Node q = p; q != null ; q = q.next){
q.left.next = q.right;
if (q.next != null) q.right.next = q.next.left;
}
}
return root;
}
public Node bfsWithQueue(Node root){
Queue<Node> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
int n = queue.size();
for (int i = 0 ; i < n; i++){
Node cur = queue.poll();
if (i + 1 < n) cur.next = queue.peek();
if (cur.left != null) queue.add(cur.left);
if (cur.right != null) queue.add(cur.right);
}
}
return root;
}
}