leetcode 938. Range Sum of BST (BST某个范围内的和)

    xiaoxiao2023-11-16  143

    题目要求

    给定一颗二叉搜索树,返回摸个范围内节点的和,包括L,R。其中BST中的值都是唯一的。

    解题思路

    对BST进行前序遍历,结果就是从小到大的顺序,所以,我们只要在遍历的时候,同时记录[L,R]范围内的数值和即可。

    主要代码c++

    class Solution { public: int sum = 0; int rangeSumBST(TreeNode* root, int L, int R) { stack<TreeNode*>s; s.push(root); while(!s.empty()) { TreeNode * tmp = s.top(); s.pop(); if(tmp) { if(tmp->val >=L && tmp->val<=R) sum += tmp->val; if(tmp->val > L) s.push(tmp->left); if(tmp->val < R) s.push(tmp->right); } } return sum; } };

    注意:本题目可以在遍历的时候直接记录数值,不需要存放在数组再计算。另外,利用BST的特性可以减少遍历的数目。

    最新回复(0)