zoukankan      html  css  js  c++  java
  • [LeetCode]Convert Sorted List to Binary Search Tree

    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.

    和上一题Convert Sorted Array to Binary Search Tree一样的道理,唯一的区别就是链表,不能直接取任意值。

    注意取链表某个值的方法,就可以写出来。方法在纸上自己画下图就明白了。

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 /**
    10  * Definition for a binary tree node.
    11  * struct TreeNode {
    12  *     int val;
    13  *     TreeNode *left;
    14  *     TreeNode *right;
    15  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    16  * };
    17  */
    18 class Solution {
    19 public:
    20     int lengthOfList(ListNode* head)
    21     {
    22         int len = 0;
    23         while(head)
    24         {
    25             len++;
    26             head = head->next;
    27         }
    28         return len;
    29     }
    30     TreeNode* createTree(ListNode* head,int left,int right)
    31     {
    32         if(left>right) return NULL;
    33         ListNode* p = head;
    34         int mid = (left+right)/2;
    35         for(int i=left;i<mid;i++) p=p->next;
    36         TreeNode* leftTree = createTree(head,left,mid-1);
    37         TreeNode* rightTree = createTree(p->next,mid+1,right);
    38         TreeNode * root = new TreeNode(p->val);
    39         root->left = leftTree;
    40         root->right = rightTree;
    41         return root;
    42     }
    43     TreeNode* sortedListToBST(ListNode* head) {
    44         int n = lengthOfList(head);
    45         createTree(head,0,n-1);
    46     }
    47 };
  • 相关阅读:
    计算机的组成与操作系统
    面向对象初识
    规范化目录
    装饰器进阶
    装饰器练习
    装饰器
    内置函数二 闭包
    生成器 推导式 练习
    迭代器 递归 格式化 练习
    生成器 推导式 内置函数
  • 原文地址:https://www.cnblogs.com/Sean-le/p/4789320.html
Copyright © 2011-2022 走看看