码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-07-26 00:07:52      阅读:59      评论:0      收藏:0      [点我收藏+]

标签: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;
    }
};

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

标签:binary   ext   root   代码   com   def   sort   public   solution   

原文地址:https://www.cnblogs.com/clown9804/p/13376061.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!