七月集训day20 二叉搜索树

二叉搜索树

  1. 节点的左子树仅包含键 小于 节点键的节点。
  2. 节点的右子树仅包含键 大于 节点键的节点。
  3. 左右子树也必须是二叉搜索树

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. 所有大于等于节点的值之和

代码/思路

  1. 将这棵树进行中序遍历以后,所有结点存储在中序遍历的数组中
  2. 对中序遍历后的结点执行后缀和操作;
/**
 * 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. 从二叉搜索树到更大和树

同上

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值