最大二叉树
class Solution
{
public:
int getmax(vector
{
int index = 0;
int max = INT_MIN;
for(int i = 0; i < vec.size(); ++i)
{
if(max < vec[i])
{
max = vec[i];
index = i;
}
}
return index;
}
TreeNode *traversal(vector
{
if(nums.empty())
{
return nullptr;
}
int index = getmax(nums);
int rootvalue = nums[index];
TreeNode root = new TreeNode(rootvalue);
if(nums.size() == 1)
{
return root;
}
vector
vector
root->left = traversal(left);
root->right = traversal(right);
return root;
}
TreeNode
if(nums.empty())
{
return nullptr;
}
return traversal(nums);
}
};
合并二叉树
class Solution {
public:
TreeNode *traversal(TreeNode root1, TreeNode root2)
{
TreeNode root;
if(root1 == nullptr && root2 == nullptr)
{
return nullptr;
}
if(root1 != nullptr && root2 == nullptr)
{
//int rootvalue = root1->val;
//root = new TreeNode(rootvalue);
return root1;
}
if(root1 == nullptr && root2 != nullptr)
{
//int rootvalue = root2->val;
//root = new TreeNode(rootvalue);
return root2;
}
if(root1 != nullptr && root2 != nullptr)
{
int rootvalue = root1->val + root2->val;
root = new TreeNode(rootvalue);
}
root->left = traversal(root1->left, root2->left);
root->right = traversal(root1->right, root2->right);
return root;
}
TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
if(root1 == nullptr && root2 == nullptr)
{
return nullptr;
}
return traversal(root1, root2);
}
};
二叉搜索树中的搜素
class Solution
{
public:
TreeNode* searchBST(TreeNode* root, int val)
{
if(root && root->val == val)
{
return root;
}
if(root == nullptr)
{
return nullptr;
}
if(root->val > val)
{
return searchBST(root->left, val);
}
else
{
return searchBST(root->right, val);
}
}
};
验证二叉搜索树
class Solution {
public:
void traversal(TreeNode root)
{
if(root == nullptr)
{
return;
}
traversal(root->left);
_vec.push_back(root->val);
traversal(root->right);
}
bool isValidBST(TreeNode root) {
if(root)
{
traversal(root);
for(int i = 0; i < _vec.size()-1; ++i)
{
if(_vec[i] >= _vec[i+1])
{
return false;
}
}
}
return true;
}
private:
vector
};