代码随想录第二十天|Leetcode654.最大二叉树、Leetcode617.合并二叉树、Leetcode700.二叉搜索树中的搜索、Leetcode98.验证二叉搜索树
Leetcode654.最大二叉树
有了之前构造二叉树的经验,这题做的很流畅
class Solution {
private:
TreeNode* traversal(vector<int>& nums){
//如果为空,直接返回
if(nums.size()==0) return NULL;
//如果为1,直接返回根节点
if(nums.size()==1){
TreeNode* root=new TreeNode(nums[0]);
return root;
}
//找到最大值,构建根节点
int maxNum=nums[0];
for(int i=1;i<nums.size();i++){
maxNum=max(maxNum,nums[i]);
}
int index;
for(index=0;index<nums.size();index++){
if(nums[index]==maxNum) break;
}
TreeNode* root=new TreeNode(maxNum);
//分割左右数组
vector<int> numsLeft(nums.begin(),nums.begin()+index);
vector<int> numsRight(nums.begin()+index+1,nums.end());
//给左右子树遍历赋值
root->left=traversal(numsLeft);
root->right=traversal(numsRight);
//返回根节点
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* result=traversal(nums);
return result;
}
};
Leetcode617.合并二叉树
class Solution {
private:
TreeNode* dfs(TreeNode* root1, TreeNode* root2){
//如果为空,返回
if(root1==NULL) return root2;
if(root2==NULL) return root1;
//12皆非空,求和
TreeNode* root=new TreeNode(root1->val+root2->val);
//dfs生成左右子树
root->left=dfs(root1->left,root2->left);
root->right=dfs(root1->right,root2->right);
//返回根
return root;
}
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
TreeNode* result=dfs(root1,root2);
return result;
}
};
Leetcode700.二叉搜索树中的搜索
class Solution {
private:
TreeNode* dfs(TreeNode* root, int val){
if(root==NULL) return NULL;
if(root->val==val) return root;
if(root->val<val) return dfs(root->right,val);
if(root->val>val) return dfs(root->left,val);
return root;
}
public:
TreeNode* searchBST(TreeNode* root, int val) {
TreeNode* result = dfs(root, val);
return result;
}
};
Leetcode98.验证二叉搜索树
二刷提醒
这道题第一遍自己没做出来
可以用数组储存中序遍历,数组递减就说明是二叉搜索树
class Solution {
private:
vector<int> vec;
void dfs(TreeNode* root){
if(root==NULL) return;
dfs(root->left);
vec.push_back(root->val);
dfs(root->right);
}
public:
bool isValidBST(TreeNode* root) {
dfs(root);
for(int i=0;i<vec.size()-1;i++){
if(vec[i]>=vec[i+1]) return false;
}
return true;
}
};
利用中序遍历的值应该是从小到大这个思路,对数组中序遍历,时刻存下当前值,带到下一次遍历里作比较,比新节点小就对,比新节点大就错。
class Solution {
public:
long long maxVal = LONG_MIN; // 因为后台测试数据中有int最小值
bool isValidBST(TreeNode* root) {
if (root == NULL) return true;
bool left = isValidBST(root->left);
// 中序遍历,验证遍历的元素是不是从小到大
if (maxVal < root->val) maxVal = root->val;
else return false;
bool right = isValidBST(root->right);
return left && right;
}
};