Convert Sorted List to Binary Search Tree (递增的链表转化成高度平衡的二叉查找树)【leetcode】

来源:互联网 发布:网络舆情试题 编辑:程序博客网 时间:2024/05/16 18:27

题目: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 binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    TreeNode *sortedListToBST(ListNode *head) {        int n=0;        ListNode *p=head;        while(p!=NULL)n++,p=p->next;        return build(head,n);            }    TreeNode *build(ListNode *head,int n)    {        if(head==NULL||n==0)return NULL;        ListNode *p=head;        for(int i=1;i<(n+1)/2;++i)p=p->next;        TreeNode *root=new TreeNode(p->val);        root->left=build(head,(n+1)/2-1);        root->right=build(p->next,n-(n+1)/2);    }};


原创粉丝点击