LeetCode-Convert Sorted List to Binary Search Tree
来源:互联网 发布:java导出excel 进度条 编辑:程序博客网 时间:2024/06/05 00:54
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
Solution:
Code:
<span style="font-size:14px;">/** * 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) return NULL; if (!head->next) return new TreeNode(head->val); ListNode *fast = head->next->next, *slow = head; while (fast && fast->next) { fast = fast->next->next; slow = slow->next; } fast = slow->next; slow->next = NULL; TreeNode *root = new TreeNode(fast->val); root->left = sortedListToBST(head); root->right = sortedListToBST(fast->next); return root; }};</span>
0 0
- 【LeetCode】Convert Sorted Array to Binary Search Tree && Convert Sorted List to Binary Search Tree
- LeetCode[Tree]: Convert Sorted List to Binary Search Tree
- [leetcode][list][dfs] Convert Sorted List to Binary Search Tree
- LeetCode: Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- LeetCode : Convert Sorted List to Binary Search Tree
- [Leetcode] Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Balanced Binary Search Tree
- [LeetCode] Convert Sorted List to Binary Search Tree
- leetcode 66: Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode Convert Sorted List to Binary Search Tree
- leetcode Convert Sorted List to Binary Search Tree
- LeetCode:Convert Sorted List to Binary Search Tree
- [LeetCode]Convert Sorted List to Binary Search Tree
- [Leetcode]Convert Sorted List to Binary Search Tree
- [leetcode]Convert Sorted List to Binary Search Tree
- Leetcode: Convert Sorted List to Binary Search Tree
- hdu-oj 1013 Digital Roots
- crontab用法
- CENTOS 使用邮箱服务
- 快速排序与二分检索法合并实现。
- JAVA使用Dom4j实现字符串和xml文件相互转换
- LeetCode-Convert Sorted List to Binary Search Tree
- Linux NFS服务器的安装与配置
- Java版opencv使用中的一些错误原因--Highgui.imread()读不进图片
- 使用单例模式实现自己的HttpClient工具类
- ZOJ-1227
- 安卓ListView优化(1)
- Windows串口通信VC++编程实例
- 中国航空博物馆之行
- KMP 算法