首页 > 其他 > 详细

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

时间:2020-02-28 18:34:45      阅读:73      评论:0      收藏:0      [点我收藏+]

题目链接:https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree/ 

给定一个单链表,其中的元素按升序排序,将其转换为高度平衡的二叉搜索树。

本题中,一个高度平衡二叉树是指一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1。

技术分享图片

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 /**
 9  * Definition for a binary tree node.
10  * struct TreeNode {
11  *     int val;
12  *     struct TreeNode *left;
13  *     struct TreeNode *right;
14  * };
15  */
16 
17 struct TreeNode* sortedListToBST(struct ListNode* head){
18     if(head==NULL) return NULL;
19     struct ListNode *slow=head,*fast=head,*tmp=head;
20     while(fast->next&&fast->next->next){
21         tmp=slow;
22         slow=slow->next;
23         fast=fast->next->next;
24     }
25     struct TreeNode *top=(struct TreeNode*)malloc(sizeof(struct TreeNode));
26     top->val=slow->val;
27     if(tmp==slow){
28         top->left=NULL;
29     }else{
30         tmp->next=NULL;
31         top->left=sortedListToBST(head);
32     }
33     top->right=sortedListToBST(slow->next);
34     return top;
35 }

 

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

原文:https://www.cnblogs.com/shixinzei/p/12378130.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!