Java Recursion, no loops, o(n)


  • 0
    J
    public void connect(TreeLinkNode root) {
        if(root == null) return;
      
        recur(root.left, root.right);
    }
    
    public void recur(TreeLinkNode left, TreeLinkNode right) {
        if(left != null && right != null) {
            left.next = right;
            if(left.right != null) left.right.next = right.left;
            recur(left.right, right.left);
            recur(left.left, left.right);
            recur(right.left, right.right);
        }
    }

  • 0
    M

    I don't think you need this statement.
    if(left.right != null) left.right.next = right.left;


  • 0
    J

    Interesting, last time I ran it it got a null pointer exception. That's why that's there.

    But i haven't tested it for my current solution.


Log in to reply
 

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