1. Full Tree Traversal (Unordered Min Search)
Intuition
Traverse every node in the tree using preorder or inorder traversal. Maintain a variable minVal. For each visited node, update minVal = min(minVal, curr.data). Returns the minimum element after visiting all N nodes in O(N) time.
When to apply: Baseline comparison for generic binary trees where BST invariants do not apply.
Algorithm
- Visit every node in the tree using DFS and maintain the global minimum.
#include <iostream>#include <algorithm>#include <climits> struct Node { int data; Node* left; Node* right; Node(int val) : data(val), left(nullptr), right(nullptr) {}}; class Solution { void dfs(Node* root, int& minVal) { if (!root) return; minVal = std::min(minVal, root->data); dfs(root->left, minVal); dfs(root->right, minVal); }public: int minValue(Node* root) { if (!root) return -1; int minVal = INT_MAX; dfs(root, minVal); return minVal; }}; int main() { Node* root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->left->left = new Node(4); Solution sol; std::cout << "Min: " << sol.minValue(root) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(H) recursion stack space