669.修剪二叉搜索树
不能仅仅只能遇到不满条件的节点就返回nullptr,因为不满足条件节点的左右子树中可能有满足条件的节点。可以“不删除不满足条件的节点”,而是寻找“满足条件的节点”
class Solution {
public:
//不用删除节点,只需要找到满足条件的节点即可
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(!root) return root;
if(root->val<low) {
return trimBST(root->right,low,high);
}
if(root->val>high) {
return trimBST(root->left,low,high);
}
root->left = trimBST(root->left,low,high);
root->right = trimBST(root->right,low,high);
return root;
}
};
108.将有序数组转换为二叉搜索树
链接:LeetCode108将有序数组转换为二叉搜索树
采用递归
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return builtBST(nums,0,nums.size()-1);
}
private:
TreeNode *builtBST(vector<int>&nums,int st,int ri){
//递归终止边界
if(st>ri) return nullptr;
int mid = ((ri-st)>>1) + st;
TreeNode * node = new TreeNode(nums[mid]);
node->left = builtBST(nums,st,mid-1);
node->right = builtBST(nums,mid+1,ri);
return node;
}
};
538.把二叉搜索树转换为累加树
链接:LeetCode538.把二叉搜索树转换为累加树
思路:
若是按照标准的中序遍历(左中右),需要先遍历整棵树,计算出所有节点的数值和,然后再次中序遍历并且记录遍历过节点的数值和presum,当前节点的数值变为sum-presum。实现起来较为繁琐。
所以采用“右中左”的类似中序遍历的方式遍历这棵树,便利的同时只需要计算遍历过节点的数值和即可。
class Solution {
public:
int cursum = 0;
TreeNode* convertBST(TreeNode* root) {
if(!root) return root;
root->right = convertBST(root->right);
int te = root->val;
if(cursum) root->val += cursum;
cursum+=te;
root->left = convertBST(root->left);
return root;
}
};