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;
    }
};

Convert Sorted List to Binary Search Tree - LeetCode

小结

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

相关文章:

  • 2021-06-07
  • 2022-02-16
  • 2021-11-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-05-31
  • 2021-12-23
  • 2021-12-30
  • 2021-10-08
  • 2021-07-24
  • 2021-06-08
相关资源
相似解决方案