Thinking of looking up middle node in linked list -- double pointer step

subject

Given a list of cells, the elements are sorted in ascending order and converted to a highly balanced BST. For this problem, a highly balanced binary tree refers to a binary tree in which the depth difference between two subtrees of each node does not exceed 1.
Example:

Given sort list: [- 10, - 3, 0, 5, 9],

Then a possible answer is: [0, -3, 9, -10, null, 5]

      0
     / \
   -3   9
   /   /
 -10  5



Code

/**
 * 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 {
private:
    TreeNode* sortedChild(ListNode* head, ListNode* tail)
    {
        if (head == tail)
            return NULL;
        if (head->next==tail)
        {
            //If there's only one element left
            TreeNode* root = new TreeNode(head->val);
            return root;
        }
        ListNode* mid = head, *temp = head;
        //Begin-----------------------
        while (temp!=tail&&temp->next!=tail)
        {
            //One forward one position, one forward two positions, the last mid will be in the middle, pay attention to the judgment conditions
            mid = mid->next;
            temp = temp->next->next;
        }
        //End-----------------------
        TreeNode* root = new TreeNode(mid->val);
        root->left = sortedChild(head, mid);
        root->right = sortedChild(mid->next, tail);
        return root;
    }
public:
    TreeNode * sortedListToBST(ListNode* head)
    {
        return sortedChild(head, NULL);
    }
};

Algorithmic thinking

What I think above is a perfect solution. I'm ashamed to say that I have the same idea about this problem. I use recursion to find the median value every time to insert the node. The essence of this solution lies in its idea of finding the middle node algorithm. It is worth recording and learning by setting the two pointer steps to 1 and 2 to find the middle position Xi, I believe that the idea of finding intermediate value can be used in many tree and linked list algorithms. I hereby record it. In addition, we should pay attention to the judgment conditions for advance!.
Related to this problem is 109. The transformation of ordered list into binary search tree is a simpler problem. Since the array is Random Access, we can get the intermediate value in O(1) time.

Posted by cptn_future on Sat, 04 Apr 2020 02:37:30 -0700