今天是二叉树
1. 654. 最大二叉树
此题还有单调栈的O(n)解法
AC代码:
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return _constructMaximumBinaryTree(nums, 0, nums.size() - 1);
}
TreeNode* _constructMaximumBinaryTree(vector<int>& nums, int left, int right) {
if (left > right) return nullptr;
int maxPos = left;
int maxVal = nums[left];
for (int i = left + 1; i <= right; ++i) {
if (nums[i] > nums[maxPos]) {
maxVal = nums[i];
maxPos = i;
}
}
TreeNode* root = new TreeNode(maxVal);
root->left = _constructMaximumBinaryTree(nums, left, maxPos - 1);
root->right = _constructMaximumBinaryTree(nums, maxPos + 1, right);
return root;
}
};
AC代码:
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1 == nullptr) return root2;
else 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;
}
};
AC代码:
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root == nullptr) return nullptr;
if(root->val == val) return root;
if(root->val < val){
return searchBST(root->right, val);
}
return searchBST(root->left, val);
}
};
class Solution {
public:
bool isValidBST(TreeNode* root) {
vector<int> nums;
inorder(nums, root);
for (int i = 1; i < nums.size(); ++i) {
if (nums[i - 1] >= nums[i]) return false;
}
return true;
}
void inorder(vector<int>& nums, TreeNode* root) {
if (root == nullptr) return;
inorder(nums, root->left);
nums.push_back(root->val);
inorder(nums, root->right);
}
};
//除了使用数组来记录中序遍历的结果外
//我们还可以使用一个pre指针来记录前一个节点
//然后比较当前节点的值是否大于pre的值
//大于,则是正确的;反之,就不是二叉搜索树
class Solution {
public:
TreeNode* pre = NULL; // 用来记录前一个节点
bool isValidBST(TreeNode* root) {
if (root == NULL) return true;
bool left = isValidBST(root->left);
if (pre != NULL && pre->val >= root->val) return false;
pre = root; // 记录前一个节点
bool right = isValidBST(root->right);
return left && right;
}
};