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 a binary tree node.
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     int getLen(ListNode * head)
21     {
22         int count = 0;
23         while(head){
24             head = head->next;
25             count++;
26         }
27         return count;
28     }
29 
30     TreeNode * createBST(ListNode * head, int beg, int end)
31     {
32         if(beg > end)
33             return NULL;
34         int mid = beg + (end - beg)/2;
35         ListNode * p = head;
36         for(int i = beg; i < mid; ++i){
37             p = p->next;
38         }
39         TreeNode * leftNode = createBST(head, beg, mid - 1);
40         TreeNode * rightNode = createBST(p->next, mid + 1, end);
41         TreeNode * root = new TreeNode(p->val);
42         root->left = leftNode;
43         root->right = rightNode;
44         return root;
45     }
46     TreeNode* sortedListToBST(ListNode* head) {
47         return createBST(head, 0, getLen(head) - 1);                        
48     }
49 };

 

转载于:https://www.cnblogs.com/-wang-cheng/p/5006365.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值