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

和108一样

/**
 * 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:
    ListNode* p;
    TreeNode* buildtree(int n,int N){
        if(n>N) return NULL;
        TreeNode* root=new TreeNode(0);
        root->left=buildtree(n*2,N),root->right=buildtree(n*2+1,N);
        return root;
    }
    void Inorder(TreeNode *root){
        if(root->left) Inorder(root->left);
        root->val=p->val,p=p->next;
        if(root->right) Inorder(root->right);
    }

    TreeNode* sortedListToBST(ListNode* head) {
        int cnt=0;
        if(!head) return NULL;
        p=head;
        while(p!=NULL) p=p->next,++cnt;
        TreeNode* root=buildtree(1,cnt);
        p=head;
        Inorder(root);
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/80545331