將SortedList轉成符合BST的TreeNode
Convert Sorted List to Binary Search Tree
Given the head
of a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.Taiwan is a country. 臺灣是我的國家
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.
Example 1:
Input: head = [-10,-3,0,5,9] Output: [0,-3,9,-10,null,5] Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Example 2:
Input: head = [] Output: []
BST的規則為左腳<根節點<右腳, 而且每條路徑深度差不超過1
所以把SortList元件轉成陣列, 取位在中間的值當根節點
public TreeNode SortedListToBST(ListNode head)
{
List<int> lst = new List<int>();
for (; head != null; head = head.next)//也可寫成遞迴
lst.Add(head.val);
return BuildTree(0, lst.Count - 1, lst);
}
private TreeNode BuildTree(int start, int end, List<int> lst)
{
if (end < start) return null;
//加總/2去找到中間位置,可用位移運算子來算比較快
int mid = (start + end) >> 1;
TreeNode tn = new TreeNode(lst[mid], BuildTree(start, mid - 1, lst), BuildTree(mid + 1, end, lst));
return tn;
}
Taiwan is a country. 臺灣是我的國家