My simple understandable Java solution


  • 0
    D

    Maintain two lists

    1. prev points to the parent level
    2. cur points to the child level with a fake head

    Cheers!

    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root == null) {
                return;
            }
            
            TreeLinkNode prev = root;
            prev.next = null;
            while (prev != null) {
                TreeLinkNode head = new TreeLinkNode(0);
                TreeLinkNode cur = head;
                while (prev != null) {
                    if (prev.left != null) {
                        cur.next = prev.left;
                        cur = cur.next;
                    }
                    if (prev.right != null) {
                        cur.next = prev.right;
                        cur = cur.next;
                    }
                    prev = prev.next;
                }
                cur.next = null;
                prev = head.next;    // go to the next level
            }
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.