一、654.最大二叉树
代码如下:
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* node = new TreeNode(0);
// 终止条件:传入的数组大小为1,遍历到叶子节点
if (nums.size() == 1) {
node->val = nums[0];
return node;
}
// 单层递归逻辑:
// 首先,查找数组中最大值和其对应的下标,最大值用来构造根节点,下标用来分割数组
int maxValue = 0;
int maxValueIndex = 0;
for (int i = 0;i < nums.size(); i++) {
if (nums[i] > maxValue) {
maxValue = nums[i];
maxValueIndex = i;
}
}
node->val = maxValue;
// 下标左区间构建左子树,左闭右开
if (maxValueIndex > 0) {
vector<int> newVec(nums.begin(), nums.begin() + maxValueIndex);
node->left = constructMaximumBinaryTree(newVec);
}
if (maxValueIndex < nums.size() - 1) {
vector<int> newVec(nums.begin() + maxValueIndex + 1, nums.end());
node->right = constructMaximumBinaryTree(newVec);
}
return node;
}
};
二、617.合并二叉树
代码如下:
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL) return root2;
if (root2 == NULL) return root1;
// 修改了root1的数值和结构
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
三、700.二叉搜索树中的搜索
代码如下:
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == NULL || root->val == val) return root;
TreeNode* result = NULL; // 定义一个result默认NULL来接住向左或向右遍历后的结果(指针)
if (root->val > val) result = searchBST(root->left, val);
if (root->val < val) result = searchBST(root->right, val);
return result;
/*可以精简一点
if (root->val > val) return searchBST(root->left, val);
if (root->val < val) return searchBST(root->right, val);
return NULL;
*/
/*迭代法
while (root != NULL) {
if (root->val > val) root = root->left;
else if (root->val < val) root = root->right;
else return root;
}
return NULL; // 经过循环都没有找到的话就返回NULL
*/
}
};
四、98.验证二叉搜索树
代码如下:
class Solution {
public:
vector<int> vec;
void traversal(TreeNode* root) {
if (root == NULL) return;
traversal(root->left);
vec.push_back(root->val);
traversal(root->right);
}
bool isValidBST(TreeNode* root) {
vec.clear();
traversal(root);
for (int i = 1; i < vec.size(); i++) {
if (vec[i] <= vec[i-1]) return false;
}
return true;
}
};