二叉树
19. 最大二叉树
思路:
每次找到最大值所在的下标,利用先序遍历的方法,递归构造二叉树
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return preorder(nums, 0, nums.size());
}
private:
TreeNode *preorder(vector<int> &nums, int start, int end) { // [start, end)
if (end - start <= 0) return nullptr;
int max = start; // 存最大值的下标
for (int i = start + 1; i < end; i++) {
if (nums[i] > nums[max]) max = i;
}
TreeNode *root = new TreeNode(nums[max]);
root->left = preorder(nums, start, max);
root->right = preorder(nums, max + 1, end);
return root;
}
};
21. 合并二叉树
思路:
对两棵子树同步遍历
- 遇到一个为空,则返回另一个
- 都不为空则相加
- 都为空,则返回空
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr && root2 == nullptr) return nullptr;
if (root1 == nullptr && root2 != nullptr) {
return root2;
}
if (root1 != nullptr && root2 == nullptr) {
return root1;
}
root1->val = root1->val + root2->val;
root1->left = mergeTrees(root1->left, root2->left);
root1->right = mergeTrees(root1->right, root2->right);
return root1;
}
};
迭代法
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (root1 == nullptr) return root2;
if (root2 == nullptr) return root1;
queue<TreeNode *> que;
que.push(root1);
que.push(root2);
while (!que.empty()) {
TreeNode *cur1 = que.front(); que.pop();
TreeNode *cur2 = que.front(); que.pop();
cur1->val += cur2->val;
if (cur1->left && cur2->left) {
que.push(cur1->left);
que.push(cur2->left);
}
if (cur1->right && cur2->right) {
que.push(cur1->right);
que.push(cur2->right);
}
if (!cur1->left && cur2->left) {
cur1->left = cur2->left;
}
if (!cur1->right && cur2->right) {
cur1->right = cur2->right;
}
}
return root1;
}
};
22. 二叉搜索树中的搜索
思路:
二分查找
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if (root == nullptr) return nullptr;
if (root->val > val) return searchBST(root->left, val);
else if (root->val < val) return searchBST(root->right, val);
return root;
}
};
迭代法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while (root) {
if (root->val > val) root = root->left;
else if (root->val < val) root = root->right;
else return root;
}
return root;
}
};
23. 验证二叉搜索树
思路:
递归的要求左子树的所有节点值小于根节点,所有右子树节点值大于根节点
看下面这个样例中,右子树中存在小于左子树的值,所以不满足。
二叉搜索树的中序遍历结果应该是一个递增序列。
class Solution {
public:
bool isValidBST(TreeNode* root) {
vector<int> orders;
midorder(root, orders);
for (int i = 1; i < orders.size(); i++) {
if (orders[i - 1] >= orders[i]) return false;
}
return true;
}
private:
void midorder(TreeNode *root, vector<int>& orders) {
if (root == nullptr) return ;
midorder(root->left, orders);
orders.push_back(root->val);
midorder(root->right, orders);
}
};
优化: 直接在遍历过程中,判断遍历结果是否递增。
class Solution {
public:
TreeNode *pre = nullptr;
bool isValidBST(TreeNode* root) {
if (root == nullptr) 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;
}
};