My super concise JAVA solution with constant space


  • 0
    J
    /**
     * Definition for binary tree with next pointer.
     * public class TreeLinkNode {
     *     int val;
     *     TreeLinkNode left, right, next;
     *     TreeLinkNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root == null) return;
            build(root.left, root.right);
        }
        
        private void build(TreeLinkNode left, TreeLinkNode right) {
            if (left == null && right == null) return;
            left.next = right;
            build(left.left, left.right);
            build(left.right, right.left);
            build(right.left, right.right);
        }
    }

  • 0
    A

    How is this constant space? What about the stack space for recursion?


Log in to reply
 

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