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
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.
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 subtree
Where i is the index of the string tree.
This article is contributed by Shubham Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
- Construct Full Binary Tree from given preorder and postorder traversals
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Construct the full k-ary tree from its preorder traversal
- Check whether a binary tree is a full binary tree or not
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Find Minimum Depth of a Binary Tree
- Depth of the deepest odd level node in Binary Tree
- Replace node with depth in a binary tree
- Sum of nodes at maximum depth of a Binary Tree
- Sum of nodes at maximum depth of a Binary Tree | Set 2
- Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
- Check if a given array can represent Preorder Traversal of Binary Search Tree
- Preorder Successor of a Node in Binary Tree
- Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
- Modify a binary tree to get preorder traversal using right pointers only
- Preorder predecessor of a Node in Binary Tree
- Find n-th node in Preorder traversal of a Binary Tree
- Write a Program to Find the Maximum Depth or Height of a Tree
- Depth of an N-Ary tree