[leetCode]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<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size;i++) {
                Node cur = queue.poll();
                if (i < size - 1) {
                    cur.next = queue.peek();
                }
               
                if (cur.left != null)
                    queue.offer(cur.left);
                if (cur.right != null)
                    queue.offer(cur.right);
            }
        }
        return root;
    }
}

使用已建立的next指针

将每一层看作是由next指针构建的一个链表,链表的头节点为每一层的最左节点,构建next指针有两种情况:

  1. 两个子节点属于同一个父节点
    这时node.left.next = node.right
  2. 两个子节点不属于同一个父节点
    使用当前层已经建立的next指针将这个两个节点相连
    node.right.next = node.nexr.left
class Solution {
    public Node connect(Node root) {
        if (root == null) return root;
        Node leftmost = root;
        while (leftmost.left != null) {
            Node head = leftmost;
            while (head != null) {
                head.left.next = head.right;
                if (head.next != null)
                    head.right.next = head.next.left;
                head = head.next;
            }
            leftmost = leftmost.left;
        }
        return root;
    }
}
posted @ 2020-10-15 09:04  消灭猕猴桃  阅读(67)  评论(0编辑  收藏  举报