654. 最大二叉树

class Solution {

public:

TreeNode* constructMaximumBinaryTree(vector& nums) {

if(nums.size()==0) return nullptr;

int max=-1;

int index;

for(int i=0;i

{

if(nums[i]>max)

{

max=nums[i];

index=i;

}

}

TreeNode* root=new TreeNode(nums[index]);

vector left(nums.begin(),nums.begin()+index);

vector right(nums.begin()+index+1,nums.end());

root->left=constructMaximumBinaryTree(left);

root->right=constructMaximumBinaryTree(right);

return root;

617. 合并二叉树

class Solution {

public:

TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {

if(root1!=nullptr&&root2!=nullptr) {root1->val=root1->val+root2->val;}

else if(root1==nullptr&&root2!=nullptr) return root2;

else if(root1!=nullptr&&root2==nullptr) return root1;

else return nullptr;

root1->right=mergeTrees(root1->right,root2->right);

root1->left=mergeTrees(root1->left,root2->left);

return root1;

}

};

700. 二叉搜索树中的搜索

class Solution {

public:

TreeNode* searchBST(TreeNode* root, int val) {

if(root==nullptr) return nullptr;

if(root->val==val) return root;

else if(root->val>val)

{

return searchBST(root->left,val);

}

else return searchBST(root->right,val);

}

};

98. 验证二叉搜索树

class Solution {

public:

void mid(TreeNode* root,vector& res)

{

if(root==nullptr) return;

mid(root->left,res);

res.push_back(root->val);

mid(root->right,res);

}

bool isValidBST(TreeNode* root) {

vector res;

mid(root,res);

for(int i=1;i

{

if(res[i]<=res[i-1]) return false;

}

return true;

}

};

需要重新做的题目 617. 合并二叉树 98. 验证二叉搜索树

推荐链接

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。