目录
669. 修剪二叉搜索树
题目链接:669. 修剪二叉搜索树
题目描述:
给你二叉搜索树的根节点 root ,同时给定最小边界low 和最大边界 high。通过修剪二叉搜索树,使得所有节点的值在[low, high]中。修剪树 不应该 改变保留在树中的元素的相对结构 (即,如果没有被移除,原有的父代子代关系都应当保留)。 可以证明,存在 唯一的答案 。
所以结果应当返回修剪好的二叉搜索树的新的根节点。注意,根节点可能会根据给定的边界发生改变。
示例:输入:root = [3,0,4,null,2,null,null,1], low = 1, high = 3
输出:[3,2,null,1]
递归!全是递归!
前序遍历:先处理当前节点,当前节点值>high,用左子树替换;当前节点值<low,用右子树替换。接着遍历左右子树。
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);
}
//当前结点值大于最大值,用其左子树代替
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;
}
}
108.将有序数组转换为二叉搜索树
题目链接:108. 将有序数组转换为二叉搜索树
也是前序遍历,每次将中间元素作为根节点。
//总是将中间靠左的元素视作根节点
struct TreeNode* deal(int* nums, int left, int right) {
if (left>right) return NULL;
int mid=left+(right-left)/2;
struct TreeNode* root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val=nums[mid];
root->left=deal(nums,left,mid-1);
root->right=deal(nums,mid+1,right);
return root;
}
struct TreeNode* sortedArrayToBST(int* nums, int numsSize) {
return deal(nums,0,numsSize-1);
}
538.把二叉搜索树转换为累加树
题目链接:538. 把二叉搜索树转换为累加树
示例:
输入:[4,1,6,0,2,5,7,null,null,null,3,null,null,null,8]
输出:[30,36,21,36,35,26,15,null,null,null,33,null,null,null,8]
遍历顺序:右中左
int sum;
struct TreeNode* deal(struct TreeNode* root){
if(root!=NULL){
//遍历右子树
deal(root->right);
//处理结点
root->val+=sum;
sum=root->val;
//遍历左子树
deal(root->left);
}
return root;
}
struct TreeNode* convertBST(struct TreeNode* root) {
sum=0;
deal(root);
return root;
}