938.二叉搜索树的范围和

在这里插入图片描述
最基本的二叉树的递归搜索运用。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int rangeSumBST(TreeNode* root, int L, int R) {
        if(!root) return 0;
        if(root->val>=L&&root->val<=R)
            return rangeSumBST(root->right,L,R)+rangeSumBST(root->left,L,R)+root->val;
        else
            return rangeSumBST(root->right,L,R)+rangeSumBST(root->left,L,R);
    }
};

在这里插入图片描述

发布了90 篇原创文章 · 获赞 7 · 访问量 2188

猜你喜欢

转载自blog.csdn.net/weixin_43784305/article/details/102622603