Try   HackMD

【LeetCode】 109. Convert Sorted List to Binary Search Tree

Description

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 of every node never differ by more than 1.

給予一個單向的串列鏈結且元素已經經過漸增排序,將它轉換為高度平衡的二元搜索樹(BST)。

這個問題中,所謂的高度平衡的二元樹被定義為一棵二元樹中所有節點的兩個子樹高度差異不大於一。

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

Solution

  • 這題我的作法其實挺暴力的,但好像也沒什麼不好的。
  • 先看看這題,基本上是一模一樣的題目,只差在給予的是linked-list還是陣列。
  • 那麼我們就將linked-list轉換成陣列就好了。

Code

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: void BST(vector<int>& nums, int s, int e, TreeNode*& n) { if(s > e) return; int mid = (s + e) / 2; n = new TreeNode(nums[mid]); BST(nums, s, mid - 1, n->left); BST(nums, mid + 1, e, n->right); } TreeNode* sortedArrayToBST(vector<int>& nums) { TreeNode* root = NULL; BST(nums, 0, nums.size() - 1, root); return root; } TreeNode* sortedListToBST(ListNode* head) { vector<int> arr; for(auto n = head; n; n = n->next) arr.push_back(n->val); return sortedArrayToBST(arr); } };
tags: LeetCode C++