654最大二叉树
思路:构造二叉树,使用前序遍历
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* constructMaximumBinaryTree(vector<int>& nums) {
TreeNode* node=new TreeNode(0);
if(nums.size()==1){
node->val=nums[0];
return node;
}
int maxValue=0;
int maxValueIndex=0;
for(int i=0;i<nums.size();i++){
if(nums[i]>maxValue){
maxValue=nums[i];
maxValueIndex=i;
}
}
node->val=maxValue;
if(maxValueIndex>0){
vector<int> newvec(nums.begin(),nums.begin()+maxValueIndex);
node->left=constructMaximumBinaryTree(newvec);
}
if(maxValueIndex<(nums.size()-1)){
vector<int>newvec(nums.begin()+maxValueIndex+1,nums.end());
node->right=constructMaximumBinaryTree(newvec);
}
return node;
}
};
617.合并二叉树
代码如下
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* mergeTrees(TreeNode* root1, TreeNode* root2) {
if(root1==NULL) return root2;
if(root2==NULL) return root1;
TreeNode* root=new TreeNode(0);
root1->val=root1->val+root2->val;
root1->left=mergeTrees(root1->left,root2->left);
root1->right=mergeTrees(root1->right,root2->right);
return root1;
}
};
700.二叉搜索树中的搜索
递归法
代码如下
class Solution {
public:
TreeNode* searchBST(TreeNode* root, int val) {
if(root==NULL||root->val==val) return root;
TreeNode *result=NULL;
if(val<root->val) result=searchBST(root->left,val);
if(val>root->val)result=searchBST(root->right,val);
return result;
}
};
迭代法
代码如下:
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 NULL;
}
};
98.验证二叉搜索树
中序遍历是有序的
递归法
代码如下
class Solution {
private:
vector<int>vec;
void traveral(TreeNode *root){
if(root==NULL) return;
traveral(root->left);
vec.push_back(root->val);
traveral(root->right);
}
public:
bool isValidBST(TreeNode* root) {
vec.clear();
traveral(root);
for(int i=1;i<vec.size();i++){
if(vec[i]<=vec[i-1])
return false;
}
return true;
}
};
不使用数组的递归法
class Solution {
public:
long long maxVal=LONG_MIN;
bool isValidBST(TreeNode* root) {
if(root==NULL) return true;
bool left=isValidBST(root->left);
if(maxVal<root->val)
maxVal=root->val;
else return false;
bool right=isValidBST(root->right);
return left&&right;
}
};