将已排序的链接列表转换为二叉搜索树

时间:2016-02-03 21:36:36

标签: algorithm binary-tree binary-search-tree

我试图实现一个算法来将已排序的链接列表转换为BST,但我没有得到所需的输出。

这是我的功能

public TreeNode linkListToBST(NodeList list) {
    TreeNode root = linkListToBSTrec(list.getHead(), list.count(list.getHead()));
    return root;
}

public TreeNode linkListToBSTrec(Node head, int n) {
    if (n <= 0) /* base case */
        return null;
    else {
        /* Recursively construct the left subtree */
        TreeNode left = linkListToBSTrec(head, n / 2);
        /*
         * Allocate memory for root, and link the above constructed left
         * subtree with root
         */
        TreeNode root = new TreeNode(head.getData());
        root.setLeft(left);
        head = head.getNext(); /*
                                 * Change head pointer of Linked List for
                                 * parent recursive calls
                                 */
        /*
         * Recursively construct the right subtree and link it with root The
         * number of nodes in right subtree is total nodes - nodes in left
         * subtree - 1 (for root) which is n-n/2-1
         */
        root.setRight(linkListToBSTrec(head, n - (n / 2) - 1));

        return root;
    }
}

调用代码段:

TreeNode root = bst.linkListToBST(list);

输入列表:1-> 2-> 3-> 4-> 5-> 6-> 7-> 8

级别顺序遍历的输出:1-> 1&gt; 2-&gt; 1-> 2-> 2-> 3-&gt;

任何帮助或答案都会非常有用:)

算法来源:Link

Link to source code

3 个答案:

答案 0 :(得分:0)

我认为你正在改变头指针的错误点。它应该在TreeNode left = linkListToBSTrec(head,n / 2);

之前

第一次,你的头和左边都是1.这就是你多次获得相同数据的原因。

我还没有实际运行该程序。通过观察它我认为头指针应该更早更改。

答案 1 :(得分:0)

我相信,您的代码并未表达您的意图。

我不熟悉Java,但您希望在函数linkListToBSTrec中传递对节点的引用,否则左递归调用中 head 的更改值将不会反映在父母的功能。

答案 2 :(得分:-1)

从排序列表构造平衡 BST的正确方法是使用树的头部作为排序列表的中间元素。然后可以递归地为中间元素左侧的元素构造左子树,同样右子树包含中间元素右侧的元素。

您使用最左边的元素作为根,这不是正确的方法。