1. Full Tree Traversal (Unpruned)
Intuition
Visit every node in the tree using preorder or inorder traversal. For each visited node, test if low <= node.val <= high. If true, increment count. This takes O(N) time regardless of whether the range contains 0 nodes or all nodes.
When to apply: Baseline comparison for generic binary trees where BST properties do not hold.
Algorithm
- Traverse every node in the tree using standard DFS/BFS and count how many satisfy
low <= node.val <= highwithout using BST properties.
#include <iostream> struct Node { int data; Node* left; Node* right; Node(int val) : data(val), left(nullptr), right(nullptr) {}}; class Solution {public: int getCount(Node* root, int l, int h) { if (!root) return 0; int count = (root->data >= l && root->data <= h) ? 1 : 0; return count + getCount(root->left, l, h) + getCount(root->right, l, h); }}; int main() { Node* root = new Node(10); root->left = new Node(5); root->right = new Node(50); root->left->left = new Node(1); root->left->right = new Node(7); root->right->left = new Node(40); root->right->right = new Node(100); Solution sol; std::cout << "Count in [5, 15]: " << sol.getCount(root, 5, 15) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(H) recursion stack