leetcode109. Ordered linked list conversion binary search tree/preorder traversal recursive construction

Topic: 109. Binary search tree conversion from ordered linked list

Given a singly linked list, the elements in it are sorted in ascending order and converted to a highly balanced binary search tree.

In this question, a highly balanced binary tree means that the absolute value of the height difference between the left and right subtrees of each node of a binary tree does not exceed 1.

Example:

给定的有序链表: [-10, -3, 0, 5, 9],

一个可能的答案是:[0, -3, 9, -10, null, 5], 它可以表示下面这个高度平衡二叉搜索树:

      0
     / \
   -3   9
   /   /
 -10  5

Source: LeetCode (LeetCode)
Link: https://leetcode-cn.com/problems/convert-sorted-list-to-binary-search-tree The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Basic idea: first order traversal recursive construction

  • Take the intermediate node of the linked list as the root, recursively construct the left and right subtrees
  • Note: When looking for an intermediate node, you need to disconnect the intermediate node from the node in front of the intermediate node; and you need to pay attention to determine whether there is a left subtree
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    
    
public:
    TreeNode* sortedListToBST(ListNode* head) {
    
    
        if(head == NULL)
            return NULL;
        // if(head->next == NULL)
        //     return new TreeNode(head->val);
        ListNode * mid;
        mid = midNode(head);
        ListNode * lhead = head, * rhead = mid->next;
        
        TreeNode * root = new TreeNode(mid->val);
        if(mid != head)//判断是否有左子树
            root->left = sortedListToBST(lhead);
        root->right = sortedListToBST(rhead);
        return root;
    }
    ListNode* midNode(ListNode* head){
    
    
        ListNode * fast = head, * slow = head, *pre = NULL;
        while(fast->next != NULL && fast->next->next != NULL){
    
    
            pre = slow;
            slow = slow->next;
            fast = fast->next->next;
        }
        if(pre)//将中间节点和前面链表断开
            pre->next = NULL;
        return slow;
    }
};

Guess you like

Origin blog.csdn.net/qq_31672701/article/details/108076385