Simple O(1) Space Java Solution with Recursive. Easy to understand!!


  • 0
    C
    public class Solution {
        public void connect(TreeLinkNode root) {
            connect(root, null);
        }
    
        private void connect(TreeLinkNode root, TreeLinkNode next) {
            if (root==null) return;
            root.next=next;
            while (true) {
                if (next==null) break;
                if (next.left!=null) {
                    next=next.left;break;
                }
                if (next.right!=null) {
                    next=next.right;break;
                }
                next=next.next;
            }
            if (root.right!=null) {
                connect(root.right, next);
                connect(root.left, root.right);
            }
            else {
                connect(root.left, next);
            }
        }
    }
    

Log in to reply
 

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