Leetcode 109. Convert Sorted List to Binary Search Tree
2018-02-08 09:12
387 查看
原题:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.
Example:Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
解决方法:
用快慢指针的方法将链表分成前后两部分,前面的做为左子节点,后面的做为右子节点。
代码:
Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees ofevery node never differ by more than 1.
Example:Given the sorted linked list: [-10,-3,0,5,9],
One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:
0
/ \
-3 9
/ /
-10 5
解决方法:
用快慢指针的方法将链表分成前后两部分,前面的做为左子节点,后面的做为右子节点。
代码:
TreeNode* sortedListToBST(ListNode* head) { if (!head) return NULL; if (!head->next) return new TreeNode(head->val); ListNode* slow = head, *fast = head->next->next; while(fast && fast->next){ slow = slow->next; fast = fast->next->next; } ListNode* cur = slow->next, *right = slow->next->next; slow->next = NULL; TreeNode* root = new TreeNode(cur->val); root->left = sortedListToBST(head); root->right = sortedListToBST(right); return root; }
相关文章推荐
- [leetcode]Merge Two Sorted Lists
- leetcode系列题目——Set Matrix Zeroes
- Leetcode 231 Power of Two 数论
- LeetCode 276. Paint Fence(篱笆涂色)
- [C++]LeetCode: 79 Next Permutation (下一个排列,常见面试题)
- 【leetcode】Spiral Matrix II (middle)
- LeetCode 31. Next Permutation
- partition-list-leetcode-C++
- leetcode 225. Implement Stack using Queues
- LeetCode No.143 Reorder List
- LeetCode111. Minimum Depth of Binary Tree
- Leetcode-sort-colors
- LeetCode 387 First Unique Character in a String
- LeetCode : Sort Colors
- 【leetcode】Palindrome Number
- LeetCode-Longest Consecutive Sequence
- leetcode刷题笔记之最长共同前缀
- Leetcode_Reverse-Words-in-a-String
- LeetCode:First Missing Positive
- leetcode 767. Reorganize String