Concise recursive Java Solution


  • 0
    A

    I know the solution should have constant space, but it is a nice way to solve this problem :)

    public class Solution {   
        public void connect(TreeLinkNode root) {
            connect(root, null);
        }
        
        private void connect(TreeLinkNode root, TreeLinkNode right) {
            if (root == null) return;
            root.next = right;
            TreeLinkNode nextRight = getNextRight(right);
            connect(root.right, nextRight);
            connect(root.left, root.right != null? root.right : nextRight);
        }
        
        private TreeLinkNode getNextRight(TreeLinkNode root) {
            if (root == null) return null;
            TreeLinkNode nextRight = root.left != null? root.left : root.right;
            return nextRight != null? nextRight : getNextRight(root.next);
        }
    }
    

Log in to reply
 

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