**654.最大二叉树 **
构造树一般采用的是前序遍历,因为先构造中间节点,然后递归构造左子树和右子树。
这题在找最大值和最大值下标的时候用了两个库函数
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
// 确定递归的终止条件 到叶子节点
TreeNode* node = new TreeNode(0);
if (nums.size() == 1) {
node->val = nums[0];
return node;
}
// 确定单层的处理逻辑
// 应该包括三部,先找到最大值构造根节点,然后递归构造左右子树
vector<int>::iterator maxiter = max_element(nums.begin(), nums.end());
int maxVal = *maxiter;
int maxValpos = distance(nums.begin(), maxiter);
// cout << maxVal << endl;
// cout << maxValpos << endl;
node->val = maxVal;
// 最大值所在的下标左区间 构造左子树
if (maxValpos > 0) {
vector<int> leftnum(nums.begin(), nums.begin() + maxValpos);
node->left = constructMaximumBinaryTree(leftnum);
}
// 最大值所在的下标左区间 构造左子树
if (maxValpos < (nums.size() - 1)) {
vector<int> rightnum(maxiter + 1, nums.end());
node->right = constructMaximumBinaryTree(rightnum);
}
return node;
}
};
又是构造二叉树,昨天大家刚刚做完 中序后序确定二叉树,今天做这个 应该会容易一些, 先看视频,好好体会一下 为什么构造二叉树都是 前序遍历
题目链接/文章讲解:https://programmercarl.com/0654.%E6%9C%80%E5%A4%A7%E4%BA%8C%E5%8F%89%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV1MG411G7ox
**617.合并二叉树 **
自己写出来的
class Solution {
public:
// 确定递归参数和返回值
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
// 确定终止条件
// 遍历到叶节点
// 如果root1为空,那么合并之后就是root2
if (root1 == nullptr)
return root2;
// 如果root2为空,那么合并之后就是root1
if (root2 == nullptr)
return root1;
// 确定单层的处理逻辑
// 把root2的值加到root1上去
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
这次是一起操作两个二叉树了, 估计大家也没一起操作过两个二叉树,也不知道该如何一起操作,可以看视频先理解一下。 优先掌握递归。
题目链接/文章讲解:https://programmercarl.com/0617.%E5%90%88%E5%B9%B6%E4%BA%8C%E5%8F%89%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV1m14y1Y7JK
**700.二叉搜索树中的搜索 **
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr || root->val == val) {
return root;
}
if (root->val > val)
return searchBST(root->left, val);
if (root->val < val)
return searchBST(root->right, val);
return nullptr;
}
};
递归和迭代 都可以掌握以下,因为本题比较简单, 了解一下 二叉搜索树的特性
题目链接/文章讲解: https://programmercarl.com/0700.%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91%E4%B8%AD%E7%9A%84%E6%90%9C%E7%B4%A2.html
视频讲解:https://www.bilibili.com/video/BV1wG411g7sF
**98.验证二叉搜索树 **
class Solution {
public:
void trival(TreeNode* root, vector<int>& result) {
if (root == nullptr)
return;
trival(root->left, result);
result.push_back(root->val);
trival(root->right, result);
}
bool isValidBST(TreeNode* root) {
// 中序遍历下,输出的二叉搜索树节点的数值是有序序列。
vector<int> result;
trival(root, result);
for (int i = 1; i < result.size(); i++) {
cout << result[i] << endl;
if (result[i - 1] >= result[i]) {
return false;
}
}
return true;
}
};
遇到 搜索树,一定想着中序遍历,这样才能利用上特性。
但本题是有陷阱的,可以自己先做一做,然后在看题解,看看自己是不是掉陷阱里了。这样理解的更深刻。
题目链接/文章讲解:https://programmercarl.com/0098.%E9%AA%8C%E8%AF%81%E4%BA%8C%E5%8F%89%E6%90%9C%E7%B4%A2%E6%A0%91.html
视频讲解:https://www.bilibili.com/video/BV18P411n7Q4