zoukankan      html  css  js  c++  java
  • LeetCode:Convert Sorted List to Binary Search Tree

    Convert Sorted List to Binary Search Tree


    Total Accepted: 67959 Total Submissions: 224265 Difficulty: Medium

    Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

    Subscribe to see which companies asked this question














    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 {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            return sortedListToBST(head, NULL);
        }
        
        TreeNode* sortedListToBST(ListNode* head, ListNode *tail) {
            
            if(head == tail) return NULL;
            
            ListNode *fast = head,*slow = head;
            while(fast!=tail && fast->next != tail){ // 找到中间结点
                fast = fast->next->next;
                slow = slow->next;
            }
            TreeNode *root = new TreeNode(slow->val);
            root->left = sortedListToBST(head, slow);
            root->right = sortedListToBST(slow->next, tail);
            return root;
        }
        
    };


  • 相关阅读:
    day69test
    day70test
    day71test
    ymfx
    day71
    day69
    day70
    day70test
    day65——day69
    c语言解决函数变参数问题 va_list
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/7305119.html
Copyright © 2011-2022 走看看