[LeetCode] Populating Next Right Pointers in Each Node


Populating Next Right Pointers in Each Node

Given a binary tree

struct TreeLinkNode {
  TreeLinkNode *left;
  TreeLinkNode *right;
  TreeLinkNode *next;
} Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.


Time Complexity
Space Complexity


Because it is a perfect binary tree. So we use a queue to keep every level. Initialize a node called pre, if it is the first node in this level, make pre equals current first node, if it is not, then pre.next = cur. When this level of bfs ends, this level's nodes are all connected.


public void connect(TreeLinkNode root) {
    //corner case
    if(root == null) return;
    Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
    TreeLinkNode pre = null;
        int size = queue.size();
        for(int i = 0; i < size; i++){
            TreeLinkNode cur = queue.poll();
            if(cur.left != null) queue.offer(cur.left);
            if(cur.right != null) queue.offer(cur.right);
            if(pre != null){
                pre.next = cur;
            pre = cur;
        pre = null;

Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous
solution still work?

My previous solution still works. :)