目录
一、删除排序列表中的重复元素
1、题目描述
2、题解
3、源码
二、二叉树的最大深度
1、题目描述
2、题解
3、源码
三、将有序数组转换成二叉搜素树
1、题目描述
2、题解
3、源码
四、将二叉搜素树变平衡
1、题目描述
2、题解
3、源码
五、平衡二叉树
1、题目描述
2、题解
3、源码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* deleteDuplicates(struct ListNode* head){
if (!head){
return head;
}
struct ListNode* cur = head;
while(cur->next) {
if(cur->val == cur->next->val) {
cur->next = cur->next->next;
}else {
cur = cur->next;
}
}
return head;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxDepth(struct TreeNode *root) {
if (root == NULL) return 0;
return fmax(maxDepth(root->left), maxDepth(root->right)) + 1;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* sortedArrayToBST(int* nums, int numsSize){
if(numsSize) {
int mediaNum = numsSize / 2;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = nums[mediaNum];
root->left = sortedArrayToBST(nums,mediaNum);
root->right = sortedArrayToBST(nums + mediaNum +1,numsSize - mediaNum - 1);
return root;
}
return NULL;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void inOrderTraverse(struct TreeNode* root,int* pos,int arr[]){//中序遍历获取二叉搜素树
if(root == NULL) return ;
inOrderTraverse(root->left,pos,arr);
arr[(*pos)++] = root->val;
inOrderTraverse(root->right,pos,arr);
}
struct TreeNode* create(int* nums,int low,int high){//对升序的数组构建平衡二叉树
if(low>high){
return ;
}
int mid = (low+high)/2;
struct TreeNode* t =(struct TreeNode*)malloc(sizeof(struct TreeNode));
t->val = nums[mid];
t->left = create(nums,low,mid - 1);
t->right = create(nums,mid + 1,high);
return t;
}
struct TreeNode* balanceBST(struct TreeNode* root){
int arr[10000];
int *pos = (int*)malloc(sizeof(int));
*pos = 0;
inOrderTraverse(root, pos, arr);
return create(arr, 0, *pos - 1);
}
int height(struct TreeNode* root){
if (root == NULL){
return 0;
}else {
return fmax(height(root->left),height(root->right)) + 1;
}
}
bool isBalanced(struct TreeNode* root){
if (root == NULL){
return true;
}else {
return fabs(height(root->left) - height(root->right)) <= 1 && isBalanced(root->left) && isBalanced(root->right);
}
}