117. Populating Next Right Pointers in Each Node II

9 阅读1分钟

image.png

Solution1 level order traversal O(N)O(N)

class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return root;
        }
        Queue<Node> queue = new LinkedList<>();
        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.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
        }
        return root;
    }
}

Solution2: using established linkedlist O(N)O(1)

  • since we dont know the structure of the tree/next level, we can know where it start. s
  • so we use a dummy head for next level.
//      while traversing the current level linkedlist, do:
//         → process left child
//          → process right child
//          → set start for the next level

class Solution {
    public Node connect(Node root) {
        if (root == null) {
            return root;
        }

        Node start = root;
       
       // loop over different levels
        while (start != null) { // start.left != null would stop early!
            Node cur = start;
            Node dummy = new Node();
            Node nextLvCur = dummy;
            // loop over cur level
            while (cur != null) {
                if (cur.left != null) {
                    nextLvCur.next = cur.left;
                    nextLvCur = nextLvCur.next;
                }
                if (cur.right != null) {
                    nextLvCur.next = cur.right;
                    nextLvCur = nextLvCur.next;
                }
                cur = cur.next; 
            }
            start = dummy.next; // move to next level
        }

        return root;
    }
}