109.有序链表转换二叉搜索树

109.有序链表转换二叉搜索树

109.有序链表转换二叉搜索树_第1张图片

题解

​ 要达到左右平衡的目的,需要有序单链表当中找到中间节点作为树的根节点的值,这样两边的高度才能差不多。需要注意的是,当单链表的节点为偶数,位于中间的两个节点都可作为根节点的值,递归建树即可。

class Solution {
    ListNode globalHead;

    public TreeNode sortedListToBST(ListNode head) {
        globalHead = head;
        int length = getLength(head);
        return buildTree(0, length - 1);
    }

    public int getLength(ListNode head) {
        int ret = 0;
        while (head != null) {
            ++ret;
            head = head.next;
        }
        return ret;
    }

    public TreeNode buildTree(int left, int right) {
        if (left > right) {
            return null;
        }
        int mid = (left + right + 1) / 2;
        TreeNode root = new TreeNode();
        root.left = buildTree(left, mid - 1);
        root.val = globalHead.val;
        globalHead = globalHead.next;
        root.right = buildTree(mid + 1, right);
        return root;
    }
}

你可能感兴趣的:(Leetcode)