654.最大二叉树
文章链接:https://programmercarl.com/0654.最大二叉树.html
题目链接:https://leetcode.cn/problems/maximum-binary-tree/description/
class Solution {
public:
TreeNode* traversal(vector<int>& nums,int left,int right){
if(left>=right) return NULL;
int maxValIndex=left;
for(int i=left;i<right;i++){
if(nums[i]>nums[maxValIndex]) maxValIndex=i;
}
TreeNode* root=new TreeNode(nums[maxValIndex]);
root->left=traversal(nums,left,maxValIndex);
root->right=traversal(nums,maxValIndex+1,right);
return root;
}
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
return traversal(nums,0,nums.size());
}
};
617.合并二叉树
文章链接:https://programmercarl.com/0617.合并二叉树.html
题目链接:https://leetcode.cn/problems/merge-two-binary-trees/description/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==NULL) return root2; //此时root2为空也没有关系,那就是空节点
if(root2==NULL) return root1;
root1->val=root1->val+root2->val; //两个都不为空
root1->left=mergeTrees(root1->left,root2->left);
root1->right=mergeTrees(root1->right,root2->right);
return root1;
}
};
700.二叉搜索树中的搜索
文章链接:https://programmercarl.com/0700.二叉搜索树中的搜索.html
题目链接:https://leetcode.cn/problems/search-in-a-binary-search-tree/description/
//递归法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL||root->val==val) return root;
if(val<root->val) return searchBST(root->left,val);
else return searchBST(root->right,val);
}
};
//迭代法
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
while(root!=NULL){
if(val<root->val) root=root->left;
else if(val>root->val) root=root->right;
else return root;
}
return root;
}
};
98.验证二叉搜索树
文章链接:https://programmercarl.com/0098.验证二叉搜索树.html
题目链接:https://leetcode.cn/problems/validate-binary-search-tree/description/
错误写法:(原因:对于一个有效的 BST,不仅需要满足左子节点的值小于根节点的值,右子节点的值大于根节点的值,还必须确保左子树所有节点的值都小于根节点,右子树所有节点的值都大于根节点。因此,仅比较直接的左、右节点是不够的。)
//以下为错误的代码!!!
class Solution {
public:
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
bool isValidLeft=true; //左子节点为空
if(root->left){
if(root->left->val<root->val) isValidLeft=isValidBST(root->left);
else return false;
}
bool isValidRight=true; //右子节点为空
if(root->right){
if(root->right->val<root->val) isValidRight=isValidBST(root->right);
else return false;
}
return isValidLeft&&isValidRight;
}
};
思路:二叉搜索树可以看它的中序序列,是从小到大的顺序!!
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;
}
};
标签:right,return,val,二叉,搜索,二叉树,TreeNode,root,left
From: https://www.cnblogs.com/VickyWu/p/18536048