代码随想录算法训练营第二十二天
654.最大二叉树
题目链接:654.最大二叉树
找数组的最大值,最大值左侧是左子树,右侧是右子树。
/**
* 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* constructMaximumBinaryTree(vector<int>& nums) {
int max_index =0;
int rootVal = INT_MIN;
if(nums.size() == 1)return new TreeNode(nums[0]);
for(int i =0;i<nums.size();i++){
if(nums[i]>rootVal){
rootVal =nums[i];
max_index = i;
}
}
TreeNode* root = new TreeNode(rootVal);
vector<int> left_nums(nums.begin(),nums.begin()+max_index);
vector<int> right_nums(nums.begin()+max_index+1,nums.end());
if(!left_nums.empty())root->left = constructMaximumBinaryTree(left_nums);//在数组传入之前判空,减少一次递归
if(!right_nums.empty())root->right = constructMaximumBinaryTree(right_nums);
return root;
}
};
617.合并二叉树
题目链接:617.合并二叉树
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==nullptr)return root2;
else if (root2 == nullptr)return root1;
int sumVal = root1->val+root2->val;
TreeNode* sumroot = new TreeNode(sumVal);
sumroot->left = mergeTrees(root1->left, root2->left);
sumroot->right = mergeTrees(root1->right, root2->right);
return sumroot;
}
};
700.二叉搜索树中的搜索
题目链接:700.二叉搜索树中的搜索
class Solution {
public:
TreeNode* result = nullptr;
TreeNode* searchBST(TreeNode* root, int val) {
if (root->val == val)
result = root;
if (root->left == nullptr && root->right == nullptr)
return nullptr;
if (root->left&&root->val > val)
searchBST(root->left, val);
else if (root->right&&root->val < val)
searchBST(root->right, val);
return result;
}
};
98.验证二叉搜索树
题目链接:98.验证二叉搜索树
不是只要左节点小于中节点小于右节点就是二叉搜索树,左子树都要小于中节点,右子树都要大于中节点。不能直接用左右节点和中节点做比较。
class Solution {
public:
TreeNode* pre = nullptr;
bool isValidBST(TreeNode* root) {
if(!root)return true;
bool left_b = isValidBST(root->left);
if(pre&&pre->val>=root->val)return false;
pre =root;
bool right_b = isValidBST(root->right);
return left_b&& right_b;
}
};