654最大二叉树
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
if (nums.empty()) return NULL;
int mnum=0;
int index=0;
for(int i=0;i<nums.size();i++)
{
if(nums[i]>mnum)
{
mnum=nums[i];
index=i;
}
}
TreeNode* root=new TreeNode(mnum);
//index==0的话只有右子树了
if(index>0)
{
vector<int>leftNums(nums.begin(), nums.begin() + index);
root->left=constructMaximumBinaryTree(leftNums);
}
if(index<nums.size()-1)
{
vector<int> rightNums(nums.begin() + index + 1, nums.end());
root->right = constructMaximumBinaryTree(rightNums);
}
return root;
}
};
617合并二叉树
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 二叉搜索树中的搜索
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val)
{
if (root == NULL||root->val ==val)return root;
TreeNode* result = NULL;
if (root->val > val) result = searchBST(root->left, val);
if (root->val < val) result = searchBST(root->right, val);
return result;
}
};
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 验证二叉搜索树
class Solution {
public:
bool isValidBST(TreeNode* root)
{
return isValid(root, nullptr, nullptr);
}
bool isValid(TreeNode* root, TreeNode* min, TreeNode* max)
{
if (root == nullptr) return true;
if (min != nullptr && root->val <= min->val) return false;
if (max != nullptr && root->val >= max->val) return false;
return isValid(root->left, min, root)
&& isValid(root->right, root, max);
}
};