【LeetCode-树】二叉搜索树的范围和

题目描述

给定二叉搜索树的根结点 root,返回 L 和 R(含)之间的所有结点的值的和。
二叉搜索树保证具有唯一的值。
示例

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

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

题目链接: https://leetcode-cn.com/problems/range-sum-of-bst/

思路

遍历整棵树就行,如果当前结点的值在 [L, R] 之间,则加入到结果中。
写法一
使用迭代,代码如下

/**
 * 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) {
        int ans = 0;
        dfs(root, L, R, ans);
        return ans;
    }

    void dfs(TreeNode* root, int L, int R, int& ans){
        if(root==nullptr) return;

        dfs(root->left, L, R, ans);
        if(L<=root->val && root->val<=R) ans += root->val;
        dfs(root->right, L, R, ans);
    }
};

可以在搜索的过程中剪枝,加快速度。代码如下:

/**
 * 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) {
        int ans = 0;
        dfs(root, L, R, ans);
        return ans;
    }

    void dfs(TreeNode* root, int L, int R, int& ans){
        if(root==nullptr) return;

        if(L<root->val) dfs(root->left, L, R, ans);
        if(L<=root->val && root->val<=R) ans += root->val;
        if(R>root->val) dfs(root->right, L, R, ans);
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(h)
    h 为树高。

写法二
使用迭代,代码如下

/**
 * 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==nullptr or L>R) return 0;

        stack<pair<TreeNode*, bool>> s;
        s.push(make_pair(root, false));
        int ans = 0;
        while(!s.empty()){
            TreeNode* curNode = s.top().first;
            bool visit = s.top().second;
            s.pop();
            if(!visit){
                if(curNode->right!=nullptr) s.push(make_pair(curNode->right, false));
                s.push(make_pair(curNode, true));
                if(curNode->left!=nullptr) s.push(make_pair(curNode->left, false));
            }else{
                if(L<=curNode->val && curNode->val<=R) ans += curNode->val;
            }
        }
        return ans;
    }
};

上面的代码写成中序遍历,其实没有必要,随便一个遍历都行。

  • 时间复杂度:O(n)
  • 空间复杂度:O(h)
    h 为树高。
原文地址:https://www.cnblogs.com/flix/p/12836872.html