[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.
Tree Depth-first Search
实现方法有两种,一种是二叉树自下往上 实现,一种是自上往下实现。我用的是后一种方法。
#include <iostream> #include <vector> using namespace std; /** * 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 n = num.size(); if(n ==0) return NULL; if(n==1) return new TreeNode(num[0]); return helpFun(num,0,n-1); } TreeNode * helpFun(vector<int> &num,int lft,int rgt) { if(lft>rgt) return NULL; if(lft==rgt) return new TreeNode(num[lft]); int mid = (lft+rgt)/2; TreeNode * curNode = new TreeNode(num[mid]); curNode->left = helpFun(num,lft,mid-1); curNode->right = helpFun(num,mid+1,rgt); return curNode; } }; int main() { return 0; }