117. 填充每个节点的下一个右侧节点指针 II

层序遍历,有点类似这道题。
104. 二叉树的最大深度

/*
// 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;
        root.next = null;
        Queue<Node> q = new LinkedList<>();
        q.offer(root);
        while (!q.isEmpty()) {
            int size = q.size();
            while (size > 0) {
                Node node = q.poll();
                if (node.left != null) q.offer(node.left);
                if (node.right != null) q.offer(node.right);
                --size;
                if (size > 0) node.next = q.peek();
                else node.next = null;
            }
        }
        return root;
    }
}

你可能感兴趣的:(LeetCode,算法,java,数据结构)