题意:给一个树,构建它的每一个节点的next节点
思路:按层遍历树,
- 每次遍历到一个节点cur时,判断它的pre节点是否为空,如果不为空,那么pre.next = cur,
- 如果是当前层的最后一个节点那么它的next为null
思想:按层遍历
复杂度:时间O(n),空间O(n)
/*
// 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)
return null;
Queue<Node> q = new LinkedList();
q.add(root);
Node pre = null;
int level = 1;
int start = 0;
int end = 1;
while(!q.isEmpty()) {
Node cur = q.poll();
start++;
if(pre != null) {
pre.next = cur;
}
pre = cur;
if(cur.left != null) {
q.add(cur.left);
end++;
}
if(cur.right != null) {
q.add(cur.right);
end++;
}
if(level == start) {
pre = null;
level = end;
}
}
return root;
}
}
网友评论