[LeetCode] Convert Sorted Array to Binary Search Tree
生活随笔
收集整理的這篇文章主要介紹了
[LeetCode] Convert Sorted Array to Binary Search Tree
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
?
Hide Tags ?Tree?Depth-first Search 方法一:遞歸,也是dfs /*** 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 *sortedArrayToBST(vector<int> &num){ int size = num.size();if(size == 0)return NULL;return sortedArrayToBSTInternal(num, 0, size - 1); } TreeNode *sortedArrayToBSTInternal(vector<int> &num, int low, int high){ // the code is very important, i.e: low = 4, hight = 5, mid = 4, // will call sortedArrayToBSTInternal(num, 4, 3)if(low > high)return NULL;if(low == high)return new TreeNode(num[low]); int mid = (high-low)/2 + low;TreeNode *root = new TreeNode(num[mid]); TreeNode *left = sortedArrayToBSTInternal(num, low, mid - 1); TreeNode *right = sortedArrayToBSTInternal(num, mid + 1, high);root->left = left;root->right= right;return root;} };?
轉載于:https://www.cnblogs.com/diegodu/p/4409809.html
總結
以上是生活随笔為你收集整理的[LeetCode] Convert Sorted Array to Binary Search Tree的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QImage与QPixmap区别
- 下一篇: 2014/4/16