Convert Sorted List to Binary Search Tree

来源:互联网 发布:python 方括号 编辑:程序博客网 时间:2024/06/05 19:30

From :https://leetcode.com/problems/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.

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; *//** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode* sortedListToBST(ListNode* head) {        return convert(head);    }        TreeNode* convert(ListNode* head) {        if(!head) return NULL;        if(!head->next) return new TreeNode(head->val);        ListNode *slow=head, *fast=head->next, *pre=NULL;        while(fast && fast->next) {            pre = slow;            slow = slow->next;            fast = fast->next->next;        }        TreeNode* root = new TreeNode(slow->val);        if(pre) {            pre->next=NULL;            root->left = convert(head);            root->right = convert(slow->next);        } else {            root->right = new TreeNode(fast->val);        }        return root;    }};


0 0
原创粉丝点击