1. Full Tree Traversal (Unpruned)
Intuition
Perform standard preorder/inorder DFS across all nodes in the tree. For each node, check if its value falls between low and high. If so, add it to the running sum. This visits all N nodes unconditionally in O(N) time.
When to apply: Baseline comparison for generic binary trees where BST ordering is absent.
Algorithm
- Traverse every node in the tree using DFS and sum all nodes that satisfy low <= node.val <= high.
#include <iostream> struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}}; class Solution {public: int rangeSumBST(TreeNode* root, int low, int high) { if (!root) return 0; int current = (root->val >= low && root->val <= high) ? root->val : 0; return current + rangeSumBST(root->left, low, high) + rangeSumBST(root->right, low, high); }}; int main() { TreeNode* root = new TreeNode(10); root->left = new TreeNode(5); root->right = new TreeNode(15); root->left->left = new TreeNode(3); root->left->right = new TreeNode(7); root->right->right = new TreeNode(18); Solution sol; std::cout << "Sum [7, 15]: " << sol.rangeSumBST(root, 7, 15) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(H) recursion stack space