zoukankan      html  css  js  c++  java
  • LeetCode 109 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.

    For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

    Example:

    Given the sorted linked list: [-10,-3,0,5,9],
    
    One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
    
          0
         / 
       -3   9
       /   /
     -10  5


    用c++的指针写,还是比较烦的‘
    c++
    class Solution {
    public:
        TreeNode* sortedListToBST(ListNode* head) {
            
             if(head==NULL) return NULL;
             int l = 0 ;
             int r = 0 ;
             ListNode* term = head;
             ListNode* left2 = NULL;
             ListNode* right2 = NULL;
            ListNode* left;
            ListNode* right;
            
             while(term!=NULL)
             {
                 r++;
                 term = term->next;
             }
            
             int mid =(l+r)/2;
             term = head;
             int value;
             l=0;
             while(term!=NULL)
             {
                if(l<mid)
                {
                    ListNode* temp = new ListNode(term->val);
                    if(left2 == NULL) {left2 = temp;left = left2;}
                    else{
                   
                    left->next = temp;
                        left = left->next;
                    }
                    
                }
                else if(l>mid)
                {
                    ListNode* temp = new ListNode(term->val);
                      if(right2 == NULL) {right2 = temp;right=right2;}
                    else{
                      right->next = temp;
                        right = right->next;
                    }
                }
                else if(l==mid)
                    value = term->val;
                term = term->next;
                 l++;
             }
           
            
             TreeNode* tree = new TreeNode(value);
             tree->left = sortedListToBST(left2);
             tree->right = sortedListToBST(right2);
            
            return tree;
            
        }
    };
  • 相关阅读:
    MongoDB面试题
    spider 爬虫文件基本参数(3)
    命令行工具(2)
    初始scrapy,简单项目创建和CSS选择器,xpath选择器(1)
    数据分析实例(离海洋距离与最高温度之间的关系分析)
    路飞业务分析
    MYSQL 主从复制,读写分离(8)
    pyquery 学习
    selenium case报错重新执行
    python小技巧
  • 原文地址:https://www.cnblogs.com/dacc123/p/9236139.html
Copyright © 2011-2022 走看看