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.
- Tree Traversals (Inorder, Preorder and Postorder)
- Find the node with minimum value in a Binary Search Tree
- Write a program to Calculate Size of a tree | Recursion
- Write a Program to Find the Maximum Depth or Height of a Tree
- Write a program to Delete a Tree
- If you are given two traversal sequences, can you construct the binary tree?
- Convert a Binary Tree into its Mirror Tree
- Given a binary tree, print out all of its root-to-leaf paths one per line.
- Lowest Common Ancestor in a Binary Search Tree.
- The Great Tree-List Recursion Problem.
- Check sum of Covered and Uncovered nodes of Binary Tree
- Level Order Tree Traversal
- Program to count leaf nodes in a binary tree
- A program to check if a binary tree is BST or not
- Check for Children Sum Property in a Binary Tree