654.最大二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* dfs_build(vector<int>& nums, int left, int right){
if(left>right) return nullptr;
int max = -1;
int index = -1;
for(int i=left; i<=right; i++){
if(nums[i]>max){
max = nums[i];
index = i;
}
}
TreeNode* node = new TreeNode(max);
node->left = dfs_build(nums, left, index-1);
node->right = dfs_build(nums, index+1, right);
return node;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* result = dfs_build(nums, 0, nums.size()-1);
return result;
}
};
参考文章:代码随想录- 654.最大二叉树
617.合并二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1 == nullptr){
return root2;
}
if(root2 == nullptr){
return root1;
}
TreeNode* node = new TreeNode(root1->val+root2->val);
node->left = mergeTrees(root1->left, root2->left);
node->right = mergeTrees(root1->right, root2->right);
return node;
}
};
参考文章:代码随想录- 617.合并二叉树
700.二叉搜索树中的搜索
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root->val==val){
return root;
}
else if(root->val>val && root->left){
return searchBST(root->left, val);
}
else if(root->val<val && root->right){
return searchBST(root->right, val);
}
else return nullptr;
}
};
参考文章:代码随想录-700.二叉搜索树中的搜索
98.验证二叉搜索树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(!root){
return true;
}
bool left = isValidBST(root->left);
bool right = isValidBST(root->right);
if(!left || !right) return false;
TreeNode* node1 = root->left;
while(node1){
if(node1->val >= root->val){
return false;
}
node1 = node1->right;
}
TreeNode* node2 = root->right;
while(node2){
if(node2->val <= root->val){
return false;
}
node2 = node2->left;
}
return true;
}
};
参考文章:代码随想录- 98.验证二叉搜索树