1. Full Tree Traversal (Unordered Max Search)
Intuition
Traverse every node in the tree using preorder or inorder traversal. Maintain a variable maxVal. For each visited node, update maxVal = max(maxVal, curr.data). Returns the maximum 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 maximum.
#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& maxVal) { if (!root) return; maxVal = std::max(maxVal, root->data); dfs(root->left, maxVal); dfs(root->right, maxVal); }public: int maxValue(Node* root) { if (!root) return -1; int maxVal = INT_MIN; dfs(root, maxVal); return maxVal; }}; int main() { Node* root = new Node(20); root->left = new Node(8); root->right = new Node(22); root->right->right = new Node(25); Solution sol; std::cout << "Max: " << sol.maxValue(root) << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N) - Space complexity:
O(H) recursion stack space