leetcode-----109. 有序链表转换二叉搜索树
Posted 景云
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-----109. 有序链表转换二叉搜索树相关的知识,希望对你有一定的参考价值。
代码
/**
* 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;
}
};
以上是关于leetcode-----109. 有序链表转换二叉搜索树的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 109. 有序链表转换二叉搜索树(Convert Sorted List to Binary Search Tree)