Shortest 15 Lines with Clarity, 2 viabiables, 2ms Java Code


  • 1
    O
    public void connect(TreeLinkNode root) {
        while (root != null) {
            for (TreeLinkNode cur = root, prev = null; cur != null; cur = cur.next) {
                if (cur.left == null && cur.right == null) continue;
                if (cur.left != null) {
                    if (prev != null) prev.next = cur.left;
                    prev = cur.left;
                }
                if (cur.right != null) {
                    if (prev != null) prev.next = cur.right;
                    prev = cur.right;
                }
            }
            for (; root != null && root.left == null && root.right == null; root = root.next);
            if (root != null)
                root = (root.left != null) ? root.left : root.right;
        }

  • 0

    Very nice solution and code, I would add some comments for additional clarity.


Log in to reply
 

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