代码随想录算法训练营第十九天|654.最大二叉树 ● 617.合并二叉树 ● 700.二叉搜索树中的搜索 ● 98.验证二叉搜索树
654.最大二叉树
题目链接:654. 最大二叉树 - 力扣(LeetCode)
思路:普通递,每层递归的思想和快排有类似之处,同时终止条件也和快排相似。但我的写法效率很低。
class Solution {
public:
TreeNode* traversal(vector<int>nums,int start,int end){
if(start>end)return NULL;
int max=nums[start];
int j=end;
for(int i=start;i<=end;i++){
if(nums[i]>=max){max=nums[i];j=i;}
}
TreeNode* result=new TreeNode(0);
result->val=max;
result->left=traversal(nums,start,j-1);
result->right=traversal(nums,j+1,end);
return result;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if(nums.size()==0)return NULL;
TreeNode* result=new TreeNode(0);
result=traversal(nums,0,nums.size()-1);
return result;
}
};
617.合并二叉树
题目链接:617. 合并二叉树 - 力扣(LeetCode)
思路:就是用所学的递归三步走,有点土味但是思路清晰,几个if一摆解决问题。
class Solution {
public:
void merge(TreeNode *root1,TreeNode* root2){
root1->val+=root2->val;
if(root1->left&&root2->left)merge(root1->left,root2->left);
if(!root1->left&&root2->left){
root1->left=new TreeNode(0);
merge(root1->left,root2->left);
}
if(root1->right&&root2->right)merge(root1->right,root2->right);
if(!root1->right&&root2->right){
root1->right=new TreeNode(0);
merge(root1->right,root2->right);
}
}
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root2==NULL)return root1;
if(root1==NULL)return root2;
merge(root1,root2);
return root1;
}
};
但很显然可以简化
class Solution {
public:
TreeNode* mergeTrees(TreeNode* t1, TreeNode* t2) {
if (t1 == NULL) return t2;
if (t2 == NULL) return t1;
// 重新定义新的节点,不修改原有两个树的结构
TreeNode* root = new TreeNode(0);
root->val = t1->val + t2->val;
root->left = mergeTrees(t1->left, t2->left);
root->right = mergeTrees(t1->right, t2->right);
return root;
}
};
700.二叉搜索树中的搜索
题目链接:700. 二叉搜索树中的搜索 - 力扣(LeetCode)
思路:由于是在二叉搜索树中搜索,所以还是很简单的。
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL)return NULL;
if(root->val==val)return root;
else if(root->val>val)return searchBST(root->left,val);
else if(root->val<val)return searchBST(root->right,val);
else return NULL;
}
};
98.验证二叉搜索树
题目链接:98. 验证二叉搜索树 - 力扣(LeetCode)
思路:一开始直接递归isValidBST发现部分样例没通过,因为不能只判断本节点和左右子节点关系,要递归判断左右子树的大小关系。因此改用中序遍历将节点存入数组后判断数组是否有序。
注意,二叉搜索树可为空但是不能有重复元素。
class Solution {
public:
void qianxu(TreeNode* node,vector<int>&result){
if(node->left) qianxu(node->left,result);
result.push_back(node->val);
if(node->right) qianxu(node->right,result);
}
bool isValidBST(TreeNode* root) {
vector<int> result;
qianxu(root,result);
for(int i=0;i<result.size()-1;i++){
if(result[i+1]<=result[i])
return false;
}
return true;
}
};
浙公网安备 33010602011771号