C++ Solution recursive


  • 0
    T
    /**
     * 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) return NULL;
            int len = len(head);
            
          	if (len == 1) return new TreeNode(head->val);
            ListNode* middle = head;
            for (int i=0; i < len/2; i++) middle = middle->next;
          	ListNode* bMiddle = head;
          	for (int i=0; i < len/2-1; i++) bMiddle = bMiddle->next;
          	bMiddle->next = NULL;
          	
          	TreeNode* root = new TreeNode(middle->val);
          	root->left = sortedListToBST(ListNode* head);
          	root->right = sortedListToBST(ListNode* middle->next);
          	return root;
        }
        
        int len(ListNode* node){
            if (!node) return 0;
            return 1 + len(node->next);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.