来自双重链表

时间:2016-05-04 05:19:03

标签: data-structures linked-list binary-search-tree doubly-linked-list tree-balancing

我正在尝试编写这个函数,它接受一个doublelyLinkedList并构建一个平衡的二叉搜索树。 TreeNode.left等同于前一个指针,TreeNode.right就像下一个指针。我从这里的程序中获取灵感,但这不起作用:

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;
}

1 个答案:

答案 0 :(得分:0)

让我试试:

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;
}

我根本没有尝试过,也许你可以尝试一下,告诉我它是否有效。