[LeetCode] Convert Sorted Array to Binary Search Tree
2015-04-09 15:31
323 查看
Given an array where elements are sorted in ascending order, convert it to a height balanced BST.
Hide Tags
Tree Depth-first Search
方法一:递归,也是dfs
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; } };
相关文章推荐
- [LeetCode] Convert Sorted Array to Binary Search Tree, Solution
- leetcode 11: Convert Sorted Array to Binary Search Tree
- leetcode - Convert Sorted Array to Binary Search Tree
- [leetcode刷题系列]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- leetcode -- Convert Sorted Array to Binary Search Tree
- [leetcode] Convert Sorted Array to Binary Search Tree
- [Leetcode 32] 108 Convert Sorted Array to Binary Search Tree
- LeetCode_Convert Sorted Array to Binary Search Tree
- LeetCode: Convert Sorted Array to Binary Search Tree
- Leetcode 108 Convert Sorted Array to Binary Search Tree
- [Leetcode] Convert Sorted Array to Binary Search Tree
- Leetcode: Convert Sorted Array to Binary Search Tree
- leetcode 11: Convert Sorted Array to Binary Search Tree
- leetcode: Convert Sorted Array to Binary Search Tree
- arrayfunction[LeetCode]Convert Sorted Array to Binary Search Tree
- [LeetCode]Convert Sorted Array to Binary Search Tree
- LeetCode Convert Sorted Array to Binary Search Tree