创作目的:为了方便自己后续复习重点,以及养成写博客的习惯。
思路:使用递归的方法,不停的判断节点与所给区间是否相符,相符则对本节点的做右节点做递归操作并返回本节点。
ledcode题目:https://leetcode.cn/problems/trim-a-binary-search-tree/
AC代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* trimBST(struct TreeNode* root, int low, int high) {
if(root == NULL) {
return NULL;
}
if(root->val < low) {
return trimBST(root->right,low,high);
}else if(root->val > high) {
return trimBST(root->left,low,high);
}else {
root->left = trimBST(root->left,low,high);
root->right= trimBST(root->right,low,high);
return root;
}
}
思路:寻找分割点,分割点作为当前节点,再递归左区间和右区间。
lecode题目:https://leetcode.cn/problems/convert-sorted-array-to-binary-search-tree/
AC代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* helper(int* nums,int left,int right)
{
if(left > right) {
return NULL;
}
//选择中间位置左边的数字作为根节点
int mid = (left + right) / 2;
struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val = nums[mid];
root->left = helper(nums,left,mid - 1);
root->right = helper(nums,mid + 1,right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
return helper(nums,0,numsSize - 1);
}
思路:累加的顺序是右中左,反中序遍历二叉树,再顺序累加。
ledcode题目:https://leetcode.cn/problems/convert-bst-to-greater-tree/description/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int sum;
struct TreeNode* dfs(struct TreeNode* root)
{
if(root != NULL) {
dfs(root->right);
sum += root->val;
root->val = sum;
dfs(root->left);
}
return root;
}
struct TreeNode* convertBST(struct TreeNode* root)
{
sum = 0;
dfs(root);
return root;
}
二叉树篇章到此结束,收获还是比较大的,坚持下去后面提升会更大。