0

I am trying to write this function that takes in a doublyLinkedList and constructs a balanced binary search tree in place. The TreeNode.left is equivalent to the previous pointer and TreeNode.right is like the next pointer. I am taking inspiration from the program here but that doesnt work:

http://www.geeksforgeeks.org/in-place-conversion-of-sorted-dll-to-balanced-bst/

private static TreeNode constructBST2(TreeNode head, int m, int n) {
    TreeNode temp = null;
    if (m < n) {
        int mid = m + (n - m)/ 2;
        TreeNode left = constructBST2(head, m, mid);
        temp = head;
        temp.left = left;
        head = head.right;
        temp.right = constructBST2(head, mid + 1, n);
    }
    return temp;
}
user1028904
  • 7,450
  • 1
  • 16
  • 7

1 Answers1

0

Let me try:

private static TreeNode constructBST2(TreeNode root, int r, int m, int n) {
    if (m < n) {
        int leftTreeMid = m + (int)Math.ceil((r - m) / 2);
        int delta = r - leftTreeMid;
        TreeNode left = root;
        for (int i = 0; i < delta; i++)
            left = left.left;
        root.left = left;
        constructBST2(left, leftTreeMid, m, r - 1);

        int rightTreeMid = r + (int)Math.ceil((n - r) / 2);
        delta = rightTreeMid - r;
        TreeNode right = root;
        for(int i = 0; i < delta; i++)
            right = right.right;
        root.right = right;
        constuctBST2(right, rightTreeMid, r + 1, n);
    }
    return root;
}

I haven't tried it at all, maybe you can try it and tell me if it works.

Jai
  • 8,165
  • 2
  • 21
  • 52
  • Actually, I'm sure the bottom most nodes (leaf nodes) of the tree would still point their left/right nodes wrongly. But if this sample code makes sense to you, then it should not be hard for you to fix that part. – Jai May 04 '16 at 06:24