LeetCode OJ - Convert Sorted List to Binary Search Tree

本文介绍如何将一个已排序的单链表转换为一个高度平衡的二叉搜索树(BST)。通过选取链表的中点作为根节点,递归地将链表分为左右两部分,并分别构建左右子树。

题目:

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

解题思路:

注意是让构造平衡二叉搜索树。

每次将链表从中间断开,分成左右两部分。左边部分用来构造左子树,右边部分用来构造右子树。递归进行求解。

代码:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 /**
10  * Definition for binary tree
11  * struct TreeNode {
12  *     int val;
13  *     TreeNode *left;
14  *     TreeNode *right;
15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
16  * };
17  */
18 class Solution {
19 public:
20     TreeNode *sortedListToBST(ListNode *head) {
21         if (head == NULL) return NULL;
22 
23         ListNode *slow = head, *fast = head, *pre = NULL;
24         do {
25             fast = fast->next;
26             if (fast == NULL) break;
27             fast = fast->next;
28             
29             pre = slow;
30             slow = slow->next;
31         } while (fast != NULL);
32 
33         TreeNode * root = new TreeNode(slow->val);
34         if (pre != NULL) {
35             pre->next = NULL;
36             root->left = sortedListToBST(head);
37         }
38         else {
39             root->left = NULL;
40         }
41         TreeNode * right_root = sortedListToBST(slow->next);
42         root->right = right_root;
43         if (pre != NULL) pre->next = slow;
44         return root;
45     }
46 };

 

转载于:https://www.cnblogs.com/dongguangqing/p/3728160.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值