654.最大二叉树
题目链接:654. 最大二叉树
class Solution {
public:
TreeNode* tree(vector<int> nums, int begin, int end){
if(begin == end) return NULL;
int index = begin, rootVal = nums[begin];
for(int i = begin + 1; i < end; ++i){
if(nums[i] > rootVal){
index = i;
rootVal = nums[i];
}
}
TreeNode* root = new TreeNode(rootVal);
if(end - begin == 1) return root;
root->left = tree(nums, begin, index);
root->right = tree(nums, index + 1, end);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* root = tree(nums, 0, nums.size());
return root;
}
};
617.合并二叉树
题目链接:617. 合并二叉树
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;
}
};
700.二叉搜索树中的搜索
题目链接:700. 二叉搜索树中的搜索
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root != NULL){
if(root->val > val) root = root->left;
else if(root->val < val) root = root->right;
else if(root->val == val) return root;
}
return NULL;
}
};
98.验证二叉搜索树
题目链接:98. 验证二叉搜索树
我的第一思路是就直接看结点,要求左孩子小于中结点,右孩子大于中结点;但是正如解析中的那样,我犯了经典的错误,因为这种大小限制不具有持续性,因为二叉搜索树要求结点的左子树全部结点都比自己小,右子树都比自己大。
所以还是先中序遍历,再判断有序性;
class Solution {
public:
vector<int> vec;
void traversal(TreeNode* cur){
if(cur == NULL) return;
if(cur->left) traversal(cur->left);
vec.push_back(cur->val);
if(cur->right) traversal(cur->right);
}
bool isValidBST(TreeNode* root) {
traversal(root);
for(int i = 0; i < vec.size() - 1; ++i){
if(vec[i] >= vec[i+1]) return false;
}
return true;
}
};
或者可以在中序遍历中确定当前结点的值是否大于前一个遍历的数值,毕竟二叉搜索树的中序遍历本来就是从小到大的;单独记录前一个遍历的结点,因为如果只是记录数值的话,后台测试数据有int最小值,尽量避免初始化最小值;
class Solution {
public:
TreeNode* pre = NULL;
bool traversal(TreeNode* cur){
if(cur == NULL) return true;
bool left = traversal(cur->left);
if(pre != NULL && cur->val <= pre->val){
return false;
}
pre = cur;
bool right = traversal(cur->right);
return left && right;
}
bool isValidBST(TreeNode* root) {
return traversal(root);
}
};