Calculate depth of a full Binary tree from Preorder
Last Updated : 23 Jul, 2025
Given the preorder sequence of a full binary tree, calculate its depth(or height) [starting from depth 0]. The preorder is given as a string with two possible characters.
'l' denotes the leaf node
'n' denotes internal node
The given tree can be seen as a full binary tree where every node has 0 or two children. The two children of a node can be 'n' or a or a mix of both.
Examples :
Input: s = "nlnll" Output: 2 Explanation: Below is the representation of the tree formed from the string with depth equals to 2.
The idea is to traverse the binary tree using preorder traversal recursively using the given preorder sequence. If the index at current node is out of bounds or the node is equal to 'l', then return 0. Otherwise, recursively traverse the left subtree and right subtree, and return 1 + max(left, right) as output.
Below is the implementation of the above approach:
Output
3
Time Complexity: O(n) ,where n is the size of array. Auxiliary Space: O(h)