Convert Sorted List to Binary Search Tree

来源:互联网 发布:淘宝恒源祥羊毛衫价格 编辑:程序博客网 时间:2024/04/30 13:10

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.


用递归的方法:

    n=0:返回Null

    n≠0:先对左子树进行构造,再对根节点进行构造,最后对右子树进行构造。

/** * 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* generate(int n){if (n==0){return NULL;}TreeNode *node = new TreeNode(0);node->left = generate(n/2);                  //先构造左子树node->val = list->val;                       //构造中节点list = list->next;                           //链表推进node->right = generate(n-n/2-1);             //构造右子树return node;}    TreeNode* sortedListToBST(ListNode* head) {        int size = 0;        this->list = head;        while(head!=NULL)        {        ++size;        head = head->next;        }        return generate(size);    }private:ListNode *list;};


0 0
原创粉丝点击