669.修剪二叉搜索树
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if(root == nullptr) return nullptr;
// 当前值小于左边界时,当前节点的左子树全部小于左边界,所以全部删除,直接处理右子树
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;
}
};
将有序数组转换为二叉搜索树
思路:二分法划分区间,将中间节点作为当前节点,左区间挂在左子树,右区间挂在右子树,保证二叉树有序平衡
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root;
root = binaryFind(nums, 0, nums.size());
return root;
}
TreeNode* binaryFind(vector<int>& nums, int left, int right) {
if(left < right) {
int mid = ((right - left) >> 1) + left;
TreeNode* node = new TreeNode(nums[mid]);
node->left = binaryFind(nums, left, mid);
node->right = binaryFind(nums, mid + 1, right);
return node;
}
return nullptr;
}
};
538.把二叉搜索树转换为累加树
此题的关键在于遍历顺序,以右中左的顺序遍历并逐渐累加结果即可
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
int count = 0;
traversal(root, count);
return root;
}
void traversal(TreeNode* root, int& count) {
if(root == nullptr) return ;
traversal(root->right, count); // 中序遍历右子树
count += root->val; // 累加结果
root->val = count;
traversal(root->left, count); // 中序遍历左子树
}
};
标签:right,TreeNode,随想录,二叉,搜索,return,root,left
From: https://www.cnblogs.com/cscpp/p/18229038