NO.109 ordered list convert binary search tree

Given a singly-linked list, wherein the elements sorted in ascending order, to convert it to a well-balanced binary search tree.

In this problem, a highly balanced binary tree is a binary tree refers to the left and right sub-tree of each node is the height difference between the absolute value of not more than 1.

Example:

Given ordered list: [-10, -3, 0, 5, 9],

One possible answer is: [0, -3, 9, -10, null, 5], it can be expressed below this height balanced binary search tree:

      0
     / \
   -3   9
   /   /
 -10  5

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
struct ListNode *helper(struct ListNode* head,int pos)
{
    while(pos>0)
    {
        head=head->next;
        pos--;
    }
    return head;
}

struct TreeNode *DFS(struct ListNode* head,int size)
{
    if(size<=0)return NULL;
    int pos=size/2;
    struct TreeNode *ret=(struct TreeNode *)malloc(sizeof(struct TreeNode ));
    struct ListNode* now=helper(head,pos);
    ret->val=now->val;
    ret->left=DFS(head,pos);
    ret->right=DFS(now->next,size-1-pos);
    return ret;
}
struct TreeNode* sortedListToBST(struct ListNode* head){
    int size=0;
    struct ListNode*tmp=head;
    while(tmp)
    {
        size++;
        tmp=tmp->next;
    }
    return DFS(head,size);
}

When execution: 24 ms, defeated 100.00% of all users in C submission

Memory consumption: 22 MB, defeated 100.00% of all users in C submission

Guess you like

Origin blog.csdn.net/xuyuanwang19931014/article/details/91420585