首页 > 其他 > 详细

Convert Sorted List to Binary Search Tree - LeetCode

时间:2019-03-22 00:28:15      阅读:204      评论:0      收藏:0      [点我收藏+]

题目链接

Convert Sorted List to Binary Search Tree - LeetCode

注意点

  • 不要访问空结点
  • 题目要求的是平衡二叉搜索树(也就是AVL树)

解法

解法一:递归,二叉搜索树的中序遍历结果刚好是一个有序数组,有序数组中间的数字刚好是根节点,因此可以用二分的思想来做。不过这道题不像数组可以直接访问中间节点,要用快慢节点的方法。

/**
 * 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:
    typedef TreeNode* Tnode;
    typedef ListNode* Lnode;
    TreeNode* sortedListToBST(ListNode* head) {
        if(!head) return NULL;
        return sortedListToBST(head,NULL);
    }
    TreeNode* sortedListToBST(Lnode head,Lnode tail) {
        if(head == tail) return NULL;
        Lnode slow = head, fast = head;
        while(fast != tail && fast->next != tail)
        {
            slow = slow->next;
            fast = fast->next->next;
        }
        Tnode n = new TreeNode(slow->val);
        n->left = sortedListToBST(head,slow);
        n->right = sortedListToBST(slow->next,tail);
        return n;
    }
};

技术分享图片

小结

  • avl的子树高度差不超过1

Convert Sorted List to Binary Search Tree - LeetCode

原文:https://www.cnblogs.com/multhree/p/10575666.html

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