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;
        }
    };
  • 相关阅读:
    线程同步(一)
    java守护线程
    C/C++中如何获取数组的长度?
    java操作xml方式比较与详解(DOM、SAX、JDOM、DOM4J)
    按单词逆序句子(含标点)
    常见误区(一)
    java创建XML及开源DOM4J的使用
    C++学习(一)
    java读XML文件
    MiniProfiler 兼容 Entity Framework 6
  • 原文地址:https://www.cnblogs.com/graph/p/3185001.html
Copyright © 2011-2022 走看看