109. 有序链表转换二叉搜索树

要求:rt
法一:可以先把链表输到数组里然后根上题一样,但耗空间
法二:每次都用快慢指针取链表中点,但耗时间
法三:可以先建好节点不赋值,按中序遍历赋值

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int len(ListNode* head){
        int length=0;
        while(head){
            head=head->next;
            ++length;
        }
        return length;
    }
    TreeNode* build(int left,int right,ListNode* &head){
        if(left>right)return nullptr;
        TreeNode* root=new TreeNode();
        int mid=(left+right)/2;
        root->left=build(left,mid-1,head);
        root->val=head->val;head=head->next;
        root->right=build(mid+1,right,head);
        return root;
    }
    TreeNode* sortedListToBST(ListNode* head) {
        return build(0,len(head)-1,head);
    }
};
上一篇:GIT安装使用


下一篇:LeetCode-437. 路径总和 III