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

题目: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);
    }
};

    原文作者:二叉查找树
    原文地址: https://blog.csdn.net/havenoidea/article/details/11778791
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞