75_leetcode_Covert Sorted List to Binary Tree

来源:互联网 发布:房屋框架设计软件 编辑:程序博客网 时间:2024/05/01 06:25

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

1:特殊情况;2:将链表分成两部分;3:注意两个子链表的头节点;4:递归实现生成两个子树


    TreeNode *sortedListToBST(ListNode *head)    {        if(head == NULL)        {            return NULL;        }             return sortedListToBSTCore(head);    }        TreeNode *sortedListToBSTCore(ListNode *head)    {        if(head == NULL)        {            return NULL;        }        if(head->next == NULL)        {            TreeNode* root = new TreeNode(head->val);            return root;        }                ListNode* slow = head;        ListNode *fast = head->next->next;        while(fast && fast->next)        {            slow = slow->next;            fast = fast->next->next;        }                int rootValue = slow->next->val;        TreeNode *root = new TreeNode(rootValue);        ListNode* secondHead = slow->next->next;        slow->next->next = NULL;        slow->next = NULL;                root->left = sortedListToBSTCore(head);        root->right =sortedListToBSTCore(secondHead);                return root;    }


0 0
原创粉丝点击