题意:根据有序链表构造平衡的二叉查找树。

/**
 * 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:
    TreeNode* sortedListToBST(ListNode* head) {
        if(head == NULL) return NULL;
        if(head -> next == NULL) return new TreeNode(head -> val);
        ListNode *fast = head;
        ListNode *slow = head;
        ListNode *pre;
        while(fast && fast -> next){
            fast = fast -> next -> next;
            pre = slow;
            slow = slow -> next;
        }
        pre -> next = NULL;
        TreeNode *root = new TreeNode(slow -> val);
        root -> left = sortedListToBST(head);
        root -> right = sortedListToBST(slow -> next);
        return root;
    }
};

  

相关文章:

  • 2021-06-15
  • 2021-12-27
  • 2022-01-16
  • 2021-05-27
  • 2021-11-11
  • 2021-10-10
  • 2021-10-24
  • 2021-06-20
猜你喜欢
  • 2022-12-23
  • 2022-02-18
  • 2021-10-18
  • 2022-02-09
相关资源
相似解决方案