LeetCode_Convert Sorted List to Binary Search Tree

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

  

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int countNodeNumb(ListNode *head)
    {
      int count = 0;
      while(head)
      {
        count++;
        head = head->next;
      }
      
      return count ;
    
    }
    TreeNode * BST(ListNode *head, int size)
    {
      if(size == 1) return  new TreeNode(head->val);
     
      int half = (size + 1 )/ 2;
      
      int count = 1;
      ListNode *pre, *p;
      pre = NULL;
      p = head;
      while(count < half)
      {
        pre = p;
        p = p->next;
        count ++ ;
      }
      TreeNode *Node = new TreeNode(p->val);
      
      Node->left = half-1 > 0 ? BST(head, half-1) : NULL ;
      Node->right = size - half > 0? BST(p->next, size - half) : NULL;
     
     return Node ;
    }
    TreeNode *sortedListToBST(ListNode *head) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        
        if(head == NULL) return NULL ;
        
        int size = countNodeNumb(head) ;
        TreeNode * myNode = BST(head, size);
        
        return myNode;
    }
};
原文地址:https://www.cnblogs.com/graph/p/3185001.html