938. 二叉搜索树的范围和(leetcode)

给定二叉搜索树的根结点 root,返回 LR(含)之间的所有结点的值的和。

二叉搜索树保证具有唯一的值。

示例 1:

输入:root = [10,5,15,3,7,null,18], L = 7, R = 15
输出:32

示例 2:

输入:root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
输出:23

提示:
树中的结点数量最多为 10000 个。
最终的答案保证小于 2^31

思路:
遍历二叉树, 同时根据LR所限定的范围进行"去枝".

题解:

/**
 * 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 sum = 0;
    void order(TreeNode* root, int L, int R) {
        if (root!=NULL) {
            if (root->val>=L&&root->val<=R) {	//判断范围
                sum += root->val;
            }
            if (root->val<=L) {					//去枝
                order(root->right, L, R);
            } else if (root->val>=R) {
                order(root->left, L, R);
            } else {
                order(root->left, L, R);
                order(root->right, L, R);
            }
        }
    }
    int rangeSumBST(TreeNode* root, int L, int R) {
        order(root, L, R);
        return sum;
    }
};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/range-sum-of-bst

发布了34 篇原创文章 · 获赞 0 · 访问量 659

猜你喜欢

转载自blog.csdn.net/acticn/article/details/104006939