654.最大二叉树
C++:
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* node=new TreeNode(0);
if(nums.size()==1){
node->val=nums[0];
return node;
}
//找到数组中最大的值和对应的下标
int maxValue=0;
int maxValueIndex=0;
for(int i=0;i<nums.size();i++){
if(nums[i]>maxValue){
maxValue=nums[i];
maxValueIndex=i;
}
}
node->val=maxValue;
//最大值所在的下标左区间
if(maxValueIndex>0){
vector<int> newVec(nums.begin(),nums.begin()+maxValueIndex);
node->left=constructMaximumBinaryTree(newVec);
}
//最大值所在的下标右区间 构造右子树
if(maxValueIndex<(nums.size()-1)){
vector<int> newVec(nums.begin()+maxValueIndex+1,nums.end());
node->right=constructMaximumBinaryTree(newVec);
}
return node;
}
};
617.合并二叉树
C++:
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==nullptr&&root2==nullptr) return nullptr;
if(root1!=nullptr&&root2==nullptr) return root1;
if(root1==nullptr&&root2!=nullptr) return root2;
root1->val+=root2->val;
root1->left=mergeTrees(root1->left,root2->left);
root1->right=mergeTrees(root1->right,root2->right);
return root1;
}
};
700.二叉搜索树中的搜索
C++:递归
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==nullptr) return nullptr;
if(val==root->val) return root;
TreeNode* temp;
if(val>root->val) temp=searchBST(root->right,val);
if(val<root->val) temp=searchBST(root->left,val);
if(temp!=nullptr) return temp;
else return nullptr;
}
};
C++:递归
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==nullptr||val==root->val) return root;
TreeNode* temp;
if(val>root->val) temp=searchBST(root->right,val);
if(val<root->val) temp=searchBST(root->left,val);
return temp;
}
};
C++:迭代
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while (root != NULL) {
if (root->val > val) root = root->left;
else if (root->val < val) root = root->right;
else return root;
}
return NULL;
}
};
98.验证二叉搜索树
c++:
class Solution {
public:
long long maxVal=LONG_MIN;
bool isValidBST(TreeNode* root) {
if(root==nullptr) 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;
}
};