Code Logo

Tree Maximum Depth

Published at25 Jul 2026
Easy 0 views
Like0

Given a string of parentheses, find the maximum nesting depth. This simulates finding the height of a tree where '(' means go deeper.

Example Input & Output

Example 1
Input
"(()())"
Output
2
Example 2
Input
"()"
Output
1
Example 3
Input
""
Output
0
Example 4
Input
"((()))"
Output
3
Example 5
Input
"(())()"
Output
2

Algorithm Flow

Recommendation Algorithm Flow for Tree Maximum Depth
Recommendation Algorithm Flow for Tree Maximum Depth

Solution Approach

function solution(s) {
  var max=0,cur=0;
  for(var i=0;i<s.length;i++){
    if(s.charAt(i)==='('){cur++;max=Math.max(max,cur);}
    else cur--;
  }
  return max;
}

Best Answers

java
class Solution {
    public int solution(String s) {
        int m=0,c=0;
        for(int i=0;i<s.length();i++){if(s.charAt(i)=='('){c++;m=Math.max(m,c);}else c--;}
        return m;
    }
}