654.最大二叉树
- 题目链接:654.最大二叉树
- 思路:构建二叉树,找到数组区间内最大值,最大值左边的区间构造左子树,最大值右边的区间构造右子树,重复即可
- 代码
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return construct(nums, 0, nums.size() - 1);
}
TreeNode* construct(const vector<int>& nums, int left, int right) {
if (left > right) {
return nullptr;
}
// 寻找最大值
int best = left;
for (int i = left + 1; i <= right; ++i) {
if (nums[i] > nums[best]) {
best = i;
}
}
TreeNode* node = new TreeNode(nums[best]);
node->left = construct(nums, left, best - 1);
node->right = construct(nums, best + 1, right);
return node;
}
};
617.合并二叉树
- 题目链接:617.合并二叉树
- 思路:一起遍历两个二叉树,同时合并两颗二叉树
- 代码:
class Solution {
public:
TreeNode *mergeTrees(TreeNode *root1, TreeNode *root2) {
if (root1 == nullptr) return root2;
if (root2 == nullptr) return root1;
return new TreeNode(root1->val + root2->val,
mergeTrees(root1->left, root2->left), // 合并左子树
mergeTrees(root1->right, root2->right)); // 合并右子树
}
};
700.二叉搜索树中的搜索
- 题目链接:700.二叉搜索树中的搜索
- 思路:遍历二叉树,节点值相等返回
- 代码
class Solution {
public:
TreeNode *searchBST(TreeNode *root, int val) {
if (root == nullptr) {
return nullptr;
}
if (val == root->val) {
return root;
}
return searchBST(val < root->val ? root->left : root->right, val);
}
};
98.验证二叉搜索树
-
题目链接:98.验证二叉搜索树
-
思路:遍历二叉树,遍历的同时确定二叉树节点值的区间,值在这个区间内即符合,如下图:
根节点的区间为负无穷到正无穷,左节点的区间为负无穷到5,右节点的区间为5到正无穷,故遍历二叉树,重复上述判断,确定节点值的区间,在区间内即符合 -
代码
class Solution {
public:
bool isTrue(TreeNode* root, long long mi, long long ma) {
if(!root)
return true;
if(root->val <= mi || root->val >= ma)
return false;
// 确定区间,区间为开区间
return isTrue(root->left, mi, root->val) && isTrue(root->right, root->val, ma);
}
bool isValidBST(TreeNode* root) {
return isTrue(root, LLONG_MIN, LLONG_MAX);
}
};