代码随想录算法训练营
Day17 代码随想录算法训练营第 17 天| LeetCode654.最大二叉树 LettCode617.合并二叉树 LeetCode700.二叉搜索树中的搜索 LeetCode98.验证二叉搜索树
目录
前言
LeetCode654.最大二叉树
LeetCode617.合并二叉树
LeetCode700.二叉搜索树中的搜索
LeetCode98.验证二叉搜索树
一、LeetCode654.最大二叉树
1.题目链接
2.思路
(1)参数和返回值
(2)边界条件
叶节点结束递归,将值赋给node->val,返回
(3)单层递归
1)求最大值及其下标,将最大值赋值给node->val
2)获取左右数组:创建新数组或用指针实现
3)递归求左右子节点
3.题解
(1)解法一:每次递归都创建新的数组来表示左右子数组
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* node=new TreeNode(0);
if(nums.size()==1)
{
node->val=nums[0];
return node;
}
int index;
int max=0;
for(int i=0;i<nums.size();i++)
{
if(max<nums[i])
{
index=i;
max=nums[i];
}
}
node->val=nums[index];
if(index>0)
{
vector<int> left (nums.begin(),nums.begin()+index);
node->left=constructMaximumBinaryTree(left);
}
if(index<nums.size()-1)
{
vector<int> right(nums.begin()+index+1,nums.end());
node->right=constructMaximumBinaryTree(right);
}
return node;
}
};
(2)解法二:每次递归不创建数组,而是移动左右指针表示左右数组
class Solution {
public:
TreeNode* construct(vector<int>& nums, int l, int r) {
TreeNode* node = new TreeNode(0);
if ((r - l) == 1) {
node->val = nums[l];
return node;
}
int index = l;
int max = 0;
for (int i = l; i < r; i++) {
if (max < nums[i]) {
index = i;
max = nums[i];
}
}
node->val = nums[index];
if (index > l) {
node->left = construct(nums, l, index);
}
if (index < r - 1) {
node->right = construct(nums, index + 1, r);
}
return node;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums, 0, nums.size());
}
};
二、LeetCode 617.合并二叉树
1.题目链接
2.思路
(1)参数和返回值
(2)边界条件
如果1号二叉树节点为空,那么新的二叉树后面的部分完全来自2号二叉树
如果2号二叉树节点为空,那么新的二叉树后面的部分完全来自1号二叉树
(3)单层递归
求新的二叉树节点的值,递归求左右子节点
3.题解
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
TreeNode* node = new TreeNode(0);
if (root1 == NULL) {
return root2;
}
if (root2 == NULL) {
return root1;
}
node->val = root1->val + root2->val;
node->left = mergeTrees(root1->left, root2->left);
node->right = mergeTrees(root1->right, root2->right);
return node;
}
};
三、LeetCode700.二叉搜索树中的搜索
1.题目链接
2.思路
(1)二叉搜索树是一个有序树
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
它的左、右子树也分别为二叉排序树
3.题解
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
TreeNode* res;
if(root==NULL)return NULL;
if(root->val==val)return root;
if(root->val>val) res= searchBST(root->left,val);
if(root->val<val)res= searchBST(root->right,val);
return res;
}
};
四、LeetCode98.验证二叉搜索树
1.题目链接
2.思路
(1)用中序遍历,得到左-中-右顺序的数组
(2)如果数组升序,则为二叉搜索树
3.题解
class Solution {
public:
void trace(TreeNode* node, vector<int>& path) {
if (node == NULL)
return;
trace(node->left, path);
path.push_back(node->val);
trace(node->right, path);
}
bool isValidBST(TreeNode* root) {
vector<int> path;
trace(root, path);
for (int i = 1; i < path.size(); i++) {
if (path[i] <= path[i - 1])
return 0;
}
return 1;
}
};