一、654 最大二叉树

int Max(int *arr,int len,int *rtval){
int index = 0;//保存最大小标
for(int i=0;i<len;i++){
if(arr[i]>arr[index]){
index = i;
}
}
*rtval = index;
return arr[index];
}
struct TreeNode*constructMaximumBinaryTree(int* nums, int numsSize) {
if(numsSize==0)
return NULL;
int i;
int max = Max(nums,numsSize,&i);
//中
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = max;
//左
root->left=constructMaximumBinaryTree(nums,i);
//右
root->right=constructMaximumBinaryTree(nums+i+1,numsSize-i-1);
return root;
}
二、617 合并二叉树

//直接改变tree1的结构
struct TreeNode* mergeTrees(struct TreeNode* root1, struct 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;
}
//这里采用创建新树的方法
struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2){
if(root1 == NULL)
return root2;
if(root2 == NULL)
return root1;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = root1->val+root2->val;//中
root->left = mergeTrees(root1->left,root2->left);//左
root->right = mergeTrees(root1->right,root2->right);//右
return root;
}
三、700 二叉搜索树中的搜索

//递归
struct TreeNode* searchBST(struct TreeNode* root, int val) {
while(root!=0){
if(root->val==val)
return root;
if(root->val<val)
return searchBST(root->right,val);
if(root->val>val)
return searchBST(root->left,val);
return NULL;
}
return root;
}
//迭代
struct TreeNode* searchBST(struct TreeNode* root, int val) {
while(root!=0){
if(root->val>val)
root = root->left;
else if(root->val<val)
root = root->right;
else
return root;
}
return NULL;
}
四、98 验证二叉搜索树

// 递归法
bool isValid(struct TreeNode* node, long long *maxVal) {
//当根节点为空时,也是一个二叉搜索树,返回true
if (node == NULL) return true;
// 递归检查左子树
bool left = isValid(node->left, maxVal);
// 检查当前节点的值是否大于之前遇到的最大值,若为二叉搜索树,则最大值会一直更新
if (*maxVal < node->val) *maxVal = node->val;
// 若当前节点的值小于等于之前的值,即不是单调递增的,说明不是二叉搜索树,返回false
else return false;
// 递归检查右子树
bool right = isValid(node->right, maxVal);
// 左子树和右子树都为二叉搜索树时,返回true
return left && right;
}
bool isValidBST(struct TreeNode* root) {
// 已遍历所有节点的最大值maxVal
long long maxVal = LONG_MIN;
return isValid(root, &maxVal);
}