Leetcode 116. Populating Next Right Pointers in Each Node
Given a binary tree:
next
pointer to point to the next right node.next
pointer should be set to NULL
.Initially, all next
pointers are set to NULL
.
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
Output:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
[0, 2^12 - 1]
.To populate each next
pointer:
The perfect binary tree property allows us to simplify this by:
// 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;
}
};
public class Solution {
public Node connect(Node root) {
if (root == null) return null;
Node leftmost = root;
while (leftmost.left != null) {
Node head = leftmost;
while (head != null) {
// Connect left -> right
head.left.next = head.right;
// Connect right -> left of next subtree, if exists
if (head.next != null) {
head.right.next = head.next.left;
}
// Move to the next node in the current level
head = head.next;
}
// Move to the next level
leftmost = leftmost.left;
}
return root;
}
}
This solution efficiently connects all next
pointers in the given binary tree.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?