Leetcode-convert-sorted-list-to-binary-search-tree(把有序链表转为二叉搜索树)

40 篇文章 0 订阅
38 篇文章 0 订阅

[编程题]convert-sorted-list-to-binary-search-tree

时间限制:1秒 空间限制:32768K

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

思路:

二分查找法每次需要找到中间元素所在节点,而链表的查找中间点
可以通过快慢指针来操作。找到中点后,要以中点的值建立
二叉搜索树的的根节点,然后需要把原链表断开,分为前后两个链表,
分别连上左右子节点即可。 
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
        return CreatBinarySearchTree(head,NULL);
    }
    TreeNode *CreatBinarySearchTree(ListNode *head,ListNode *tail){
        if(head == tail) return NULL;
        ListNode *pSlower = head;
        ListNode *pFaster = head;
        while(pFaster!=tail && pFaster->next!=tail){
            pSlower = pSlower->next;
            pFaster = pFaster->next->next;
        }
        TreeNode *BSTroot = new TreeNode(pSlower->val);
        BSTroot->left = CreatBinarySearchTree(head,pSlower);
        BSTroot->right = CreatBinarySearchTree(pSlower->next,tail);
        return BSTroot;
    }
};

这个是网上看到的解法基本同理我觉得更好理解一点,可读性更高

class Solution {
public:
    TreeNode *sortedListToBST(ListNode *head) {
             if(head==NULL) return NULL;
             ListNode *pFaster=head,*pSlower=head,*prev=NULL;
             while(pFaster!=NULL&&pFaster->next!=NULL){
                   pFaster=pFaster->next->next;
                   prev=pSlower;
                   pSlower=pSlower->next;
             }
             TreeNode *root=new TreeNode(pSlower->val);
             if(prev!=NULL){
                 prev->next=NULL;
                 root->left=sortedListToBST(head);
             }
             if(pSlower->next!=NULL){
                 root->right=sortedListToBST(pSlower->next);
             }
             return root;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值