- 654.最大二叉树
- 617.合并二叉树
- 700.二叉搜索树中的搜索
- 98.验证二叉搜索树
654.最大二叉树 先找到最大值和其索引,然后再根据val来分左右边
TreeNode* GetLR(vector<int>& nums) {
TreeNode* root = new TreeNode(nums[0]);
if (nums.size() == 1)
return root;
int max = INT_MIN;
int val;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > max) {
max = nums[i];
val = i;
}
}
TreeNode* root1 = new TreeNode(max);
if (val > 0) {//说明这次的最大值不是在最左边
vector<int> left = {nums.begin(), nums.begin() + val};
root1->left = GetLR(left);
}
if (val < nums.size() - 1) {//说明这次的最大值不是在最右边
vector<int> right = {nums.begin() + val + 1, nums.end()};
root1->right = GetLR(right);
}
return root1;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return GetLR(nums);
}
617.合并二叉树 搞清楚终止条件
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {//直接相加就是了,
if(root1==nullptr)return root2;
if(root2==nullptr)return root1;
root1->val+=root2->val;
root1->left= mergeTrees(root1->left,root2->left);
root1->right= mergeTrees(root1->right,root2->right);
return root1;
}
700.二叉搜索树中的搜索 二叉搜素树特性 大于val在右边,小于在左边
TreeNode* searchBST(TreeNode* root, int val) {
// 终止条件
if (root == nullptr)
return nullptr;
// 中左右
if (root->val == val)
return root;
if (root->val > val) {
root= searchBST(root->left, val);
} else {
root= searchBST(root->right, val);
}
return root;
}
98.验证二叉搜索树 中序遍历,值会比前一个大
TreeNode* pre=nullptr;
bool isValidBST(TreeNode* root) {
if(root==nullptr)return true;
bool left=isValidBST(root->left);
if(pre!=nullptr&&pre->val>=root->val){
return false;
} pre=root;
bool right=isValidBST(root->right);
return left&&right;
}