题1:
指路:LeetCode654 最大二叉树
思路与代码:
这个题思路不难,找到最大值使其成为根节点即可。再递归左子树和右子树即可完成最大二叉树的构造。代码如下:
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* node = new TreeNode(0);
// 递归终止
if (nums.size() == 1) {
node->val = nums[0];
return node;
}
// 单层递归逻辑
int MaxValue = 0;
int index = 0;
for (int i = 0; i < nums.size(); i++) {
if (nums[i] > MaxValue) {
MaxValue = nums[i]; // 找到最大值
index = i ; // 找到最大值的下标为之后左右分割数组做准备
}
}
node->val = MaxValue;
// 向左递归
if (index > 0) {
vector<int> vec1(nums.begin(), nums.begin() + index); // 左闭右开
node->left = constructMaximumBinaryTree(vec1);
}
// 向右递归
if (index < nums.size() - 1) {
vector<int> vec2(nums.begin() + index + 1, nums.end()); // 左闭右开
node->right = constructMaximumBinaryTree(vec2);
}
return node;
}
};
优化代码:
class Solution {
private:
TreeNode* traversal(vector<int>& nums, int left, int right) {
if (left >= right) return nullptr;
// 分割点下标
int index = left;
for (int i = left + 1; i < right; ++i) {
if (nums[i] > nums[index]) index = i;
}
TreeNode* root = new TreeNode(nums[index]);
root->left = traversal(nums, left, index);
root->right = traversal(nums, index + 1, right);
return root;
}
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return traversal(nums, 0, nums.size());
}
};
题2:
指路:LeetCode617 合并二叉树
思路与代码:
题意明了思路清晰,跟着题意来即可。唯一需要注意的是终止条件。代码如下:
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == NULL) return root2;
if (root2 == NULL) return root1;
root1->val += root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
题3:
指路:LeetCode700 二叉搜索树中的搜索
思路与代码:
这个题的题意也是相当清晰,递归左右子树即可。代码如下:
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == NULL) return NULL;
if (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;
}
};
题4:
指路:LeetCode98 验证二叉搜索树
思路与代码:
典型的递归题。需要注意的是不能只简单地判断是否是左节点值小于中间节点值,中间节点值小于有节点值(我第一遍就是这么写的,然后就game over了)。而是左子树的所有节点都小于中间节点,而中间节点又都小于右子树的所有节点。最后是初始化最小值成longlong_min。代码如下:
class Solution {
public:
long long maxVal = LONG_MIN;
bool isValidBST(TreeNode* root) {
if (root == NULL) return true;
bool left = isValidBST(root->left);
if (maxVal < root->val) maxVal = root->val;
else return false;
bool right = isValidBST(root->right);
return left && right;
}
};