二叉搜索树
- 节点的左子树仅包含键 小于 节点键的节点。
- 节点的右子树仅包含键 大于 节点键的节点。
- 左右子树也必须是二叉搜索树
938. 二叉搜索树的范围和
代码/思路
class Solution {
public:
int rangeSumBST(TreeNode *root, int low, int high) {
if (root == nullptr) {
return 0;
}
if (root->val > high) {
return rangeSumBST(root->left, low, high);
}
if (root->val < low) {
return rangeSumBST(root->right, low, high);
}
return root->val + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high);
}
};
剑指 Offer II 054. 所有大于等于节点的值之和
代码/思路
- 将这棵树进行中序遍历以后,所有结点存储在中序遍历的数组中
- 对中序遍历后的结点执行后缀和操作;
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<TreeNode* >iod;
void dfs(TreeNode* root)
{
if(root)
{
dfs(root->left);
iod.push_back(root);
dfs(root->right);
}
}
public:
TreeNode* convertBST(TreeNode* root) {
dfs(root);
for(int i = iod.size() - 2; i >= 0; i--)
{
iod[i]->val += iod[i + 1] ->val;
}
return root;
}
};
538. 把二叉搜索树转换为累加树
同上
1038. 从二叉搜索树到更大和树
同上