• [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.

    这题的关键是能找出当前链表的中间节点,然后再递归左右的子链表,开始的时候程序先计算链表总厂,然后传入两个前后索引指针,最后每次递归找出中间节点即可。

     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 binary tree
    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 calLen(ListNode *node)
    21     {
    22         int len = 0;
    23         while(node)
    24         {
    25             len++;
    26             node = node->next;
    27         }
    28         return len;
    29     }
    30     
    31     TreeNode *createTree(ListNode *node, int left, int right)
    32     {
    33         if (left > right)
    34             return NULL;
    35             
    36         int mid = (left + right) / 2;
    37         
    38         ListNode *p = node;
    39         
    40         for(int i = left; i < mid; i++)
    41             p = p->next;
    42             
    43         TreeNode *leftNode = createTree(node, left, mid - 1);
    44         TreeNode *rightNode = createTree(p->next, mid + 1, right);
    45         
    46         TreeNode *tNode = new TreeNode(p->val);
    47         
    48         tNode->left = leftNode;
    49         tNode->right = rightNode;
    50         
    51         return tNode;        
    52     }
    53     
    54     TreeNode *sortedListToBST(ListNode *head) {
    55         // Start typing your C/C++ solution below
    56         // DO NOT write int main() function
    57         int len = calLen(head);
    58         return createTree(head, 0, len - 1);
    59     }
    60 };

     

  • 相关阅读:
    随笔35 内联函数
    随笔32 内部类,外部类,局部内部类
    随笔31 Spring的依赖注入的三种方式
    随笔30 抽象类与接口
    随笔29 Statement对象
    随笔28 Spring中的事务
    随笔27 面向对象的五大基本原则
    随笔26 java中的泛型
    html5学习笔记——HTML5 web存储
    html5学习笔记——HTML 5 视频
  • 原文地址:https://www.cnblogs.com/chkkch/p/2744805.html
Copyright © 2020-2023  润新知