Accepted Java recursive solution


  • 3

    The recursive solution of my last post, although the space is not O(1) (due to recursion), the solution is still elegant.

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

Log in to reply
 

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