simple Java solution


  • 0
    J
        public void connect(TreeLinkNode root) {
            if (root == null || root.left == null && root.right == null) return;
            connect(root, null);
        }
        
        private void connect(TreeLinkNode root, TreeLinkNode sibling) {
            root.next = sibling;
            if (root.right != null) connect(root.right, findSibling(sibling));
            if (root.left != null) connect(root.left, root.right != null ? root.right : findSibling(sibling));
        }
        
        private TreeLinkNode findSibling(TreeLinkNode node) {
            while (node != null) {
                if (node.left != null) return node.left;
                if (node.right != null) return node.right;
                node = node.next;
            }
            return null;
        }
    

Log in to reply
 

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