标签:binary ext root 代码 com def sort public solution
/**
* 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* sortedListToBST(ListNode* head) {
if (!head) return NULL;
int n = 0;
for (auto p = head; p; p = p->next) n++;
if (n == 1) return new TreeNode(head->val);
auto cur = head;
for (int i = 0; i < n / 2 - 1; ++i) cur = cur->next;
auto root = new TreeNode(cur->next->val);
root->right = sortedListToBST(cur->next->next);
cur->next = NULL;
root->left = sortedListToBST(head);
return root;
}
};
标签:binary ext root 代码 com def sort public solution
原文地址:https://www.cnblogs.com/clown9804/p/13376061.html