本文主要是介绍Leetcode 108 Convert Sorted Array to Binary Search Tree(二叉树),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目连接:Leetcode 108 Convert Sorted Array to Binary Search Tree
解题思路:每次取范围中间的数作为当前结点的值。
/*** 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:TreeNode* buildTree(int start, int end, vector<int>& nums) {if (start > end) return NULL;int mid = (start + end) >> 1;TreeNode* ret = new TreeNode(nums[mid]);if (start == end) return ret;ret->left = buildTree(start, mid-1, nums);ret->right = buildTree(mid+1, end, nums);return ret;}TreeNode* sortedArrayToBST(vector<int>& nums) {if (nums.size() == 0) return NULL;return buildTree(0, nums.size()-1, nums);}
};
这篇关于Leetcode 108 Convert Sorted Array to Binary Search Tree(二叉树)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!