论坛首页 编程语言技术论坛

[Leetcode] Convert Sorted List to Binary Search Tree

浏览 1178 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-09-11  
<div class="iteye-blog-content-contain" style="font-size: 14px;"> <div id="question_109" class="row-odd question-title" style="margin: 0px; padding: 5px 8px; border: 1px solid #f8f8f8; font-size: 13px; vertical-align: baseline; background-color: #f8f8f8; cursor: pointer; color: #222222; font-family: 'Helvetica Neue', arial, sans-serif;"> <strong style="margin: 0px; padding: 0px; border: 0px; vertical-align: baseline; background-color: transparent;">Convert Sorted List to Binary Search Tree</strong><span class="date" style="margin: 0px 10px 0px 0px; padding: 0px; border: 0px; font-size: 10px; vertical-align: baseline; background-color: transparent; color: #999999; float: right;" title="2012-10-03 00:35:00">Oct 3 '12</span><span class="stats" style="margin: 0px; padding: 1px 4px; border: 0px; font-size: 11px; vertical-align: baseline; background-color: #eeeeee; color: #999999; width: 65px; text-align: center;" title="5768 accepted submissions out of 16298 (35%)">5768 / 16298</span> </div> <div class="row-odd question-content" style="margin: 0px; padding: 5px 8px 5px 55px; border: 1px solid #f8f8f8; font-size: 13px; vertical-align: baseline; background-color: #f8f8f8; color: #222222; font-family: 'Helvetica Neue', arial, sans-serif;"> <p style="margin-bottom: 20px; border: 0px; vertical-align: baseline; background-color: transparent;">Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.</p> </div> <p> </p> <p> </p> <pre name="code" class="cpp">/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *sortedListToBST(ListNode *head) { if (head == NULL) return NULL; ListNode* t = head; int len = 0; while (t != NULL) len++, t = t-&gt;next; return gen(head, 0, len - 1); } TreeNode *gen(ListNode* &amp;cur, int start, int end) { if (start &gt; end) return NULL; int mid = start + (end -start) / 2; TreeNode *left = gen(cur, start, mid - 1); TreeNode *node = new TreeNode(cur-&gt;val); cur = cur-&gt;next; node-&gt;left = left; node-&gt;right = gen(cur, mid+1, end); } };</pre> <p> </p> </div>
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics