654.最大二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
//构造二叉树的题一律用前序遍历,中左右:因为要先构造中结点
struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize) {
//题目规定数组大于等于1→不用考虑数组为空的情况
if (numsSize == 1) {//叶子结点直接返回,不用再递归
struct TreeNode* node =
(struct TreeNode*)calloc(1, sizeof(struct TreeNode));
node->val = nums[0];
return node;
}
int max_value = INT_MIN;
int max_index = 0;
for (int i = 0; i < numsSize; i++) {
if (nums[i] > max_value) {
max_index = i;
max_value = nums[i];
}
}
struct TreeNode* node =
(struct TreeNode*)calloc(1, sizeof(struct TreeNode));
node->val = max_value;
if(max_index>0){//保证数组元素个数>=1
node->left=constructMaximumBinaryTree(nums,max_index);
}
if(max_index<numsSize-1){//保证数组元素个数>=1
//记得-1
node->right=constructMaximumBinaryTree(nums+max_index+1,numsSize-max_index-1);
}
return node;
}
617.合并二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* mergeTrees(struct TreeNode* root1, struct TreeNode* root2) {
if (!root1)
return root2;
if (!root2)
return root1;
//注意在C语言别忘了申请空间
struct TreeNode* node =
(struct TreeNode*)calloc(1, sizeof(struct TreeNode));
node->val = root1->val += root2->val;
node->left = mergeTrees(root1->left, root2->left);
node->right = mergeTrees(root1->right, root2->right);
return node;
}
700.二叉搜索树中的搜索
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* searchBST(struct TreeNode* root, int val) {
while(root){
if(root->val>val) root=root->left;
else if(root->val<val) root=root->right;
else{
return root;
}
}
return NULL;
}
98.验证二叉搜索树
//中序遍历有序即为二叉搜索树
//max_value要定义成long long类型的最小值,因为题目输入可能含int最小值,此时若max_value=INT_MIN 则会判断错误
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool in_order(struct TreeNode* root, struct TreeNode** pre) {
if (!root)
return true;
bool left = in_order(root->left, pre);
//判断当前结点是否满足
if (*pre && (*pre)->val >= root->val)
return false;
// pre==NULL时,此时为最左侧结点,不用比较前驱
*pre = root;
//要使用二级指针,不然只会改变递归调用某一层的pre,而不会改变全局的pre
bool right = in_order(root->right, pre);
return left && right; //左右子树也要判断
}
bool isValidBST(struct TreeNode* root) {
struct TreeNode** pre=(struct TreeNode**)calloc(1,sizeof(struct TreeNode*));
return in_order(root, pre); }