LeetCode 654 最大二叉树
和昨天的中序、后序遍历构建二叉树很像,只是昨天需要注释掉的地方,今天注释掉会报错,需要加上去了。
class Solution {
public:
TreeNode* mybuildTree(vector<int>& nums, int l, int r) {
if (l > r) return nullptr;
if (l == r) {
TreeNode* cur = new TreeNode(nums[l]);
return cur;
}
int maxNum = 0;
int maxIndex = 0;
for (int i = l; i <= r; i++) {
if (maxNum < nums[i]) {
maxNum = nums[i];
maxIndex = i;
}
}
TreeNode* cur = new TreeNode(maxNum);
cur->left = mybuildTree(nums, l, maxIndex - 1);
cur->right = mybuildTree(nums, maxIndex + 1, r);
return cur;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return mybuildTree(nums, 0, nums.size() - 1);
}
};
LeetCode 617 合并二叉树
用递归也是一样很容易做
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if (!root1 && !root2) return root1;
if (root1 && !root2) return root1;
if (!root1 && root2) return root2;
TreeNode* cur = new TreeNode(root1->val + root2->val);
cur->left = mergeTrees(root1->left, root2->left);
cur->right = mergeTrees(root1->right, root2->right);
return cur;
}
};
这题迭代法暂时还不会写,后面需要加强。
LeetCode 700 二叉搜索树中的搜索
这题首先是二叉搜索树,要比较大小直接用一个cur指针进行类似二分查找的操作就行了
代码如下:
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
TreeNode* cur = root;
while (cur && cur->val != val) {
if (cur->val < val) cur = cur->right;
else if (cur->val > val) cur = cur->left;
}
return cur;
}
};
LeetCode 98 验证二叉搜索树
这题其实不是很难,将二叉搜索树按中序遍历遍历一遍后看数组是否严格递增就行了。只是我在写中序遍历的时候,把它和层序遍历用的队列弄混了,断点打了好几次,还是没找出来,最后一拍脑门才发现这个错误,读者要引以为戒啊!
代码如下:
class Solution {
public:
bool isValidBST(TreeNode* root) {
TreeNode* cur = root;
stack<TreeNode*> mysta;
vector<int> inorder;
while (cur || !mysta.empty()) {
while (cur) {
mysta.push(cur);
cur = cur->left;
}
cur = mysta.top();
mysta.pop();
inorder.push_back(cur->val);
cur = cur->right;
}
for (int i = 0; i < inorder.size() - 1; i++) {
if (inorder[i + 1] <= inorder[i]) return false;
}
return true;
}
};