Solving Maximum Depth of N-ary Tree with DFS and BFS

Day 30/100 — Solved “Maximum Depth of N-ary Tree” . today, A simple problem on the surface, but a great exercise to reinforce recursive thinking and traversal strategies. Approach 1: Depth-First Search (DFS) Used recursion to explore each branch of the tree as deep as possible. For every node, I computed the depth of all its children and took the maximum among them. The final answer for each node becomes 1 + max depth of its children. Base cases handled: If the node is null → depth = 0 If the node has no children → depth = 1 This approach is intuitive and closely follows the definition of depth itself. Approach 2: Breadth-First Search (BFS) Traversed the tree level by level using a queue. Each iteration processes one full level of nodes, and the depth counter increments after finishing each level. This approach is useful when thinking in terms of layers rather than paths. Complexity: Both approaches run in O(n) time since every node is visited once. Space complexity differs based on recursion depth (DFS) vs queue size (BFS). Key takeaway: Understanding both DFS and BFS gives flexibility in tackling tree problems from different perspectives—path-based vs level-based thinking. #Day30 #100DaysOfCode #DSA #LeetCode #Python #CodingJourney #Algorithms #DataStructures #ProblemSolving

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories