Where am I going wrong?


  • 0
    S

    This code works, but it fails to set appropriate nulls for left or right child. Please tell me where am I going wrong. Thanks!

        public TreeNode sortedListToBST(ListNode head) {
            if (head == null) {
                return null;
            }
            
            if (head.next == null) {
                return new TreeNode(head.val);
            }
            
            ListNode slow = head, fast = head;
            ListNode prev = null;
            
            while (fast != null && fast.next != null) {
                prev = slow;
                slow = slow.next;
                fast = fast.next.next;
            }
            
            TreeNode root = new TreeNode(slow.val);
            prev.next = null;
            root.left = sortedListToBST(head);
            root.right = sortedListToBST(slow.next);
            
            return root;
        }
    }

Log in to reply
 

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