zoukankan      html  css  js  c++  java
  • 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;
        }
    };
  • 相关阅读:
    HashMap源码解析
    深入理解Java字符串
    Netty粘包、半包
    Netty源码分析-Future和Promise
    Lock简介
    一、Netty中的EventLoop
    对象实例化内存布局与访问定位
    运行时数据区概述及线程
    TCP三次握手和四次挥手
    Redis线程IO模型-Redis 单线程为什么还能这么快?
  • 原文地址:https://www.cnblogs.com/graph/p/3185001.html
Copyright © 2011-2022 走看看