博文中会简要介绍Leetcode P0108题目分析及解题思路。
“Convert Sorted Array to Binary Search Tree”是比较简单和基础的树的题目,运用了深度优先搜索,这里是递归回溯的思路。这道题需要我们构造一个平衡二叉搜索树,我们可以每次将整个数组二分,其中点作为BST的根结点,然后运用递归回溯的思路,向下层生长。
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.
以下是Java的题解代码实现。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode sortedArrayToBST(int[] nums) {
if (nums == null || nums.length == 0)
return null;
return this.build(nums, 0, nums.length-1);
}
private TreeNode build(int[] nums, int left, int right) {
if (left > right)
return null;
int mid = (left+right)/2;
TreeNode root = new TreeNode(nums[mid]);
root.left = this.build(nums, left, mid-1);
root.right = this.build(nums, mid+1, right);
return root;
}
}
以下是C++的题解代码实现。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
if (nums.size() == 0)
return NULL;
return this->Build(nums, 0, nums.size()-1);
}
private:
TreeNode* Build(vector<int> &nums, int left, int right) {
if (left > right)
return NULL;
if (left == right)
return new TreeNode(nums[left]);
int mid = (left+right)/2;
TreeNode *root = new TreeNode(nums[mid]);
root->left = this->Build(nums, left, mid-1);
root->right = this->Build(nums, mid+1, right);
return root;
}
};