第一题:Leetcode669. 修剪二叉搜索树
题目描述
思路
本题是二叉搜索树,其根节点大于所有左子树节点取值,小于所有右子树节点取值,因此存在三种情况:
- [low,high]区间完全位于root的左子树,在左子树进行修剪并返回修剪完的左子树即可。
- [low,high]区间完全位于root的右子树,在右子树进行修剪并返回修剪完的右子树即可。
- [low,high]区间跨越root根节点,修剪左子树和右子树,并返回root。
题解1——递归法
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr)
return root;
if (root->val > high)
return trimBST(root->left, low, high);
else if (root->val < low)
return trimBST(root->right, low, high);
root->left = trimBST(root->left, low, high);
root->right = trimBST(root->right, low, high);
return root;
}
};
题解2——迭代法
class Solution {
public:
TreeNode* trimBST(TreeNode* root, int low, int high) {
if (root == nullptr)
return root;
while (root != nullptr && (root->val > high || root->val < low)) {
if (root->val > high)
root = root->left;
else
root = root->right;
}
TreeNode* cur = root;
while (cur != nullptr) {
while (cur->left && cur->left->val < low)
cur->left = cur->left->right;
cur = cur->left;
}
cur = root;
while (cur != nullptr) {
while (cur->right && cur->right->val > high)
cur->right = cur->right->left;
cur = cur->right;
}
return root;
}
};
其实从cur定义以后我不太能看懂了就。
第二题:Leetcode108. 将有序数组转换为二叉搜索树
题目描述
解题思路
对于一个二叉搜索树,平衡二叉树建立起来很简单。将nums中间的元素作为根节点,左边的数组建立左子树,右边的数组建立右子树即可。
Utils函数的参数left和right分别为待建立树的数组区域,左闭右闭。
题解
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return sortedArrayToBSTUtils(nums, 0, nums.size() - 1);
}
TreeNode* sortedArrayToBSTUtils(vector<int>& nums, int left, int right) {
if (left > right)
return nullptr;
int mid = left + (right - left) / 2;
TreeNode* root = new TreeNode(nums[mid]);
if (left == right)
return root;
root->left = sortedArrayToBSTUtils(nums, left, mid - 1);
root->right = sortedArrayToBSTUtils(nums, mid + 1, right);
return root;
}
};
第三题:Leetcode538. 把二叉搜索树转换为累加树
题目描述
解题思路
使用 右 中 左顺序遍历二叉树,使用一个PreSum变量记录前一个计算出来的 sum值,此次遍历取值:
题解——迭代法
class Solution {
public:
TreeNode* convertBST(TreeNode* root) {
convertBSTUtil(root);
return root;
}
void convertBSTUtil(TreeNode* root) {
long pre = 0;
stack<TreeNode*> mystack;
TreeNode* cur = root;
// 右
while (cur != nullptr || !mystack.empty()) {
if (cur != nullptr) {
mystack.push(cur);
cur = cur->right;
} else {
cur = mystack.top(), mystack.pop();
cur->val += pre;
pre = cur->val;
cur = cur->left;
}
}
}
};