Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balanced binary search tree.
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
给定一个内部元素按照升序排列的数组,请将其转化成高度平衡的二叉搜索树。
输入 | 输出 |
---|---|
nums = [-10,-3,0,5,9] | [0,-3,9,-10,null,5] |
nums = [1,3] | [3,1] |
IDE:VS2019
IDE版本:16.10.1
语言:c++11
#include "Solution.h"
#include <vector> // std::vector
#include<iostream> // std::cout
using namespace std;
// 主程序
int main()
{
// 输入
vector<int> nums= { -10, -3, 0, 5, 9 };
Solution solution; // 实例化Solution
TreeNode* output = solution.sortedArrayToBST(nums); // 主功能
}
#pragma once
#include<vector> // std::vector
#include<algorithm>
using namespace std;
//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 nullptr; // 空数组情况
int mid = nums.size() / 2; // 定义中点值
TreeNode* node = new TreeNode(nums[mid]);
auto leftTree = vector<int>(nums.begin(), nums.begin() + mid); // 左边树结构
auto rightTree = vector<int>(nums.begin() + mid + 1, nums.end()); // 右边树结构
if (mid != 0) // 左边树结构递归
node->left = sortedArrayToBST(leftTree); // 递归
if (mid != nums.size() - 1)
node->right = sortedArrayToBST(rightTree);
return node;
}
};
参考:https://blog.csdn.net/u012814856/article/details/77894863
参考:
https://blog.csdn.net/u012814856/article/details/77894863
最主要的作用就是封装。封装的好处就是可以再次利用。让使用者不必关心这个是什么,只要根据定义使用就可以了。
class中默认的成员访问权限是private的,而struct中则是public的。 (2)class继承默认是private继承,而从struct继承默认是public继承。
参考:https://blog.csdn.net/qq_33973359/article/details/105511966
参考:https://www.cnblogs.com/qyaizs/articles/2039101.html
参考:https://www.cnblogs.com/zhengfa-af/p/8144786.html
Leetcode No.108 Convert Sorted Array to Binary Search Tree(c++实现)
原文:https://www.cnblogs.com/yunmeng-shi/p/14977295.html