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

    // 168ms
    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 TreeNode *sortedListToBST(ListNode *head,int len) { 21 int mid=len/2,tem; 22 tem=mid; 23 TreeNode *root,*left,*right; 24 ListNode *p,*q,*r; 25 p=head; 26 27 q=NULL; 28 while(tem) 29 { 30 tem--; 31 q=p; 32 p=p->next; 33 } 34 root=new TreeNode(p->val); 35 36 if(mid) 37 root->left=sortedListToBST(head,mid); 38 if(len-mid-1) 39 root->right=sortedListToBST(p->next,len-mid-1); 40 return root; 41 } 42 TreeNode *sortedListToBST(ListNode *head) { 43 // Start typing your C/C++ solution below 44 // DO NOT write int main() function 45 ListNode *p=head; 46 if(head==NULL) 47 return NULL; 48 49 int count=0; 50 while(p) 51 { 52 count++; 53 p=p->next; 54 } 55 return sortedListToBST(head,count); 56 } 57 };
  • 相关阅读:
    Linux 命令集合
    vsftpd 创建虚拟用户
    Java Web Socket
    Linux 命令集合
    YII 1.0 上传文件
    YII 1.0 扩展第三方类
    YII 1.0 发表文章用到的小物件
    YII 1.0 增删改查
    mysql 日志
    YII 1.0 小功能总结
  • 原文地址:https://www.cnblogs.com/mengqingzhong/p/3118290.html
Copyright © 2011-2022 走看看