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.

     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     TreeNode* convert(ListNode *&head, int len) {
    21         if (len <= 0) return NULL;
    22         TreeNode *left = convert(head, len / 2);
    23         TreeNode *root = new TreeNode(head->val);
    24         root->left = left;
    25         head = head->next;
    26         root->right = convert(head, len - 1 - len / 2);
    27         return root;
    28     }
    29     TreeNode* sortedListToBST(ListNode* head) {
    30         ListNode *p = head;
    31         int len = 0;
    32         while (p != NULL) {
    33             ++len;
    34             p = p->next;
    35         }
    36         return convert(head, len);
    37     }
    38 };
  • 相关阅读:
    单例模式
    反射常见方法
    字符流,字节流总结
    泛型限定
    随机数判断最值
    字符流与字节流练习
    文件常见操作属性
    文件过滤器
    字符流读取文件
    目前最流行的IT编程语言
  • 原文地址:https://www.cnblogs.com/easonliu/p/4892840.html
Copyright © 2011-2022 走看看