LeetCode—109. Convert Sorted List to Binary Search Tree

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


给定一个链表,求出它的平衡二叉树。

同数组相同,寻找根节点。设两个指针f、s,分别每步走两个指针和一个指针,当f到末尾后,s指向的就是中间节点。


class Solution {

public:

    TreeNode* sortedListToBST(ListNode* head) {

      if(head == NULL || head -> next == NULL)

            return head == NULL ? NULL : new TreeNode(head -> val);


        // 找到中间节点

        ListNode *f = head -> next -> next, *s = head;

        while(f != NULL && f -> next != NULL)

        {

            f = f -> next -> next;

            s = s -> next;

        }


        ListNode *l = head, *m = s -> next, *r = m -> next;

        s -> next = NULL;


        TreeNode *root = new TreeNode(m -> val);

        root -> left = sortedListToBST(l);

        root -> right = sortedListToBST(r);


        return root;

    }

};

你可能感兴趣的:(LeetCode—109. Convert Sorted List to Binary Search Tree)