116.填充每个节点的下一个右侧节点指针
方法:层次遍历
/*
// 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 root;}Queue<Node> queue = new LinkedList<Node>();queue.add(root);while(!queue.isEmpty()){int size = queue.size();for(int i = 0;i<size;i++){//从队首取出元素Node node = queue.poll();if(i < size - 1){//获取队列第一个元素但不删除node.next = queue.peek();}if(node.left != null){queue.add(node.left);}if(node.right != null){queue.add(node.right);}}}//返回根节点return root;}
}