Calculate depth of a full Binary tree from Preorder - GeeksforGeeks

20 May, 2021
Given preorder of a 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‘n’ denotes internal node
‘l’ denotes the leaf
‘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 ‘n’ or ‘l’ or mix of both.Examples :  
Input  : nlnll
Output : 2
Explanation :
Input  : nlnnlll
Output : 3
 
Preorder of the binary tree is given so traverse Also, we would be given a string of char (formed of ‘n’ and ‘l’), so there is no need to implement tree also.The recursion function would be: 1) Base Case: return 0; when tree[i] = ‘l’ or i >= strlen(tree) 2) find_depth( tree[i++] ) //left subtree 3) find_depth( tree[i++] ) //right subtreeWhere i is the index of the string tree. 
C++
Java
Python3
C#
Javascript
// C++ program to find height of full binary tree// using preorder#include <bits/stdc++.h>using namespace std; // function to return max of left subtree height// or right subtree heightint findDepthRec(char tree[], int n, int& index){    if (index >= n || tree[index] == 'l')        return 0;     // calc height of left subtree (In preorder    // left subtree is processed before right)    index++;    int left = findDepthRec(tree, n, index);     // calc height of right subtree    index++;    int right = findDepthRec(tree, n, index);     return max(left, right) + 1;} // Wrapper over findDepthRec()int findDepth(char tree[], int n){    int index = 0;    findDepthRec(tree, n, index);} // Driver programint main(){    // Your C++ Code    char tree[] = "nlnnlll";    int n = strlen(tree);     cout << findDepth(tree, n) << endl;     return 0;}
// Java program to find height// of full binary tree using// preorderimport java .io.*; class GFG{    // function to return max    // of left subtree height    // or right subtree height    static int findDepthRec(String tree,                            int n, int index)    {        if (index >= n ||            tree.charAt(index) == 'l')            return 0;         // calc height of left subtree        // (In preorder left subtree        // is processed before right)        index++;        int left = findDepthRec(tree,                                n, index);         // calc height of        // right subtree        index++;        int right = findDepthRec(tree, n, index);         return Math.max(left, right) + 1;    }     // Wrapper over findDepthRec()    static int findDepth(String tree,                         int n)    {        int index = 0;        return (findDepthRec(tree,                             n, index));    }     // Driver Code    static public void main(String[] args)    {        String tree = "nlnnlll";        int n = tree.length();        System.out.println(findDepth(tree, n));    }} // This code is contributed// by anuj_67.
#Python program to find height of full binary tree# using preorder     # function to return max of left subtree height# or right subtree heightdef findDepthRec(tree, n, index) :     if (index[0] >= n or tree[index[0]] == 'l'):        return 0     # calc height of left subtree (In preorder    # left subtree is processed before right)    index[0] += 1    left = findDepthRec(tree, n, index)     # calc height of right subtree    index[0] += 1    right = findDepthRec(tree, n, index)    return (max(left, right) + 1) # Wrapper over findDepthRec()def findDepth(tree, n) :     index = [0]    return findDepthRec(tree, n, index)          # Driver program to test above functionsif __name__ == '__main__':    tree= "nlnnlll"    n = len(tree)     print(findDepth(tree, n)) # This code is contributed by SHUBHAMSINGH10
// C# program to find height of// full binary tree using preorderusing System; class GFG {     // function to return max of left subtree    // height or right subtree height    static int findDepthRec(char[] tree, int n, int index)    {        if (index >= n || tree[index] == 'l')            return 0;         // calc height of left subtree (In preorder        // left subtree is processed before right)        index++;        int left = findDepthRec(tree, n, index);         // calc height of right subtree        index++;        int right = findDepthRec(tree, n, index);         return Math.Max(left, right) + 1;    }     // Wrapper over findDepthRec()    static int findDepth(char[] tree, int n)    {        int index = 0;        return (findDepthRec(tree, n, index));    }     // Driver program    static public void Main()    {        char[] tree = "nlnnlll".ToCharArray();        int n = tree.Length;        Console.WriteLine(findDepth(tree, n));    }} // This code is contributed by vt_m.
<script>    // Javascript program to find height of    // full binary tree using preorder         // function to return max of left subtree    // height or right subtree height    function findDepthRec(tree, n, index)    {        if (index >= n || tree[index] == 'l')            return 0;          // calc height of left subtree (In preorder        // left subtree is processed before right)        index++;        let left = findDepthRec(tree, n, index);          // calc height of right subtree        index++;        let right = findDepthRec(tree, n, index);          return Math.max(left, right) + 1;    }      // Wrapper over findDepthRec()    function findDepth(tree, n)    {        let index = 0;        return (findDepthRec(tree, n, index));    }         let tree = "nlnnlll".split('');    let n = tree.length;    document.write(findDepth(tree, n));     </script>
Output: 
3
Time Complexity: O(N)
Auxiliary Space: O(1)
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=RCfG0Bw75rk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
vt_m
SHUBHAMSINGH10
rohitsingh07052
divyeshrabadiya07
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
Level Order Binary Tree Traversal
AVL Tree | Set 1 (Insertion)
Inorder Tree Traversal without Recursion
Binary Tree | Set 3 (Types of Binary Tree)
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not