Maximum Depthof Binary Tree Algorithm

The Maximum Depth of Binary Tree Algorithm is an essential technique in computer science used to determine the maximum depth or height of a binary tree. A binary tree is a data structure in which each node has at most two children, typically referred to as the left and right child. The depth of a node is the number of edges from the root to that node, and the maximum depth of a binary tree is the length of the longest path from the root node down to the farthest leaf node. This algorithm is crucial in various applications, such as optimizing search and sort operations, balancing trees for efficient data access, and solving various tree-based problems in programming and data analysis. The algorithm for finding the maximum depth of a binary tree can be implemented using recursion or iteration. In the recursive approach, the maximum depth is calculated by traversing the tree from the root node down to each leaf node, following both left and right children, and incrementing the depth count at each level. The base case is reached when there are no more children to traverse, and the maximum depth is the maximum of the depths obtained from both left and right subtrees plus one (for the root node). In the iterative approach, a depth-first search (DFS) strategy can be employed using a stack data structure to store nodes and their corresponding depths. The algorithm iterates through the tree, visiting each node and pushing its children onto the stack while updating the maximum depth encountered so far. The algorithm terminates when all nodes have been visited, and the maximum depth is returned as the result.
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL)
            return 0;
        int lf = 1 + maxDepth(root->left);
        int rt = 1 + maxDepth(root->right);
        return max(lf, rt);
    }
};

LANGUAGE:

DARK MODE: