Try   HackMD

【LeetCode】 108. Convert Sorted Array to Binary Search Tree

Description

Given an array 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)。

對於這個問題,一個高度平衡的二元樹被定義為所有節點的兩個子樹,高度相差都不大於1的二元樹。

Example:

Given the sorted array: [-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

  • 要建立一個平衡的BST並不難,我們只要確定每次建立節點時都挑選中間的元素,就可以讓樹不會往某一邊歪斜。
  • 我的作法是將陣列的中間值設為該節點的值,然後用剩下陣列的左半邊建立左子樹,右半邊建立右子樹。

Code

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ 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; } };
tags: LeetCode C++