The Wayback Machine - https://web.archive.org/web/20241005003635/https://www.geeksforgeeks.org/calculate-depth-full-binary-tree-preorder/
Open In App

Calculate depth of a full Binary tree from Preorder

Last Updated : 11 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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. 

  1. ‘l’ denotes the leaf
  2. ‘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 subtree

Where i is the index of the string tree. 

Implementation:

C++




// 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 height
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 max(left, right) + 1;
}
  
// Wrapper over findDepthRec()
int findDepth(char tree[], int n)
{
    int index = 0;
    return findDepthRec(tree, n, index);
}
  
// Driver program
int main()
{
    // Your C++ Code
    char tree[] = "nlnnlll";
    int n = strlen(tree);
  
    cout << findDepth(tree, n) << endl;
  
    return 0;
}


Java




// Java program to find height 
// of full binary tree using
// preorder
import 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.


Python3




#Python program to find height of full binary tree 
# using preorder
      
# function to return max of left subtree height 
# or right subtree height 
def 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 functions 
if __name__ == '__main__':
    tree= "nlnnlll"
    n = len(tree) 
  
    print(findDepth(tree, n))
  
# This code is contributed by SHUBHAMSINGH10


C#




// C# program to find height of
// full binary tree using preorder
using 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.


Javascript




<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)



Previous Article
Next Article

Similar Reads

Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
Given two binary trees S and T, the task is the check that if S is a subtree of the Tree T. For Example: Input: Tree T - 1 / \ 2 3 / \ / \ 4 5 6 7 Tree S - 2 / \ 4 5 Output: YES Explanation: The above tree is the subtree of the tree T, Hence the output is YES Approach: The idea is to traverse both the tree in Pre-order Traversal and check for each
11 min read
Construct Full Binary Tree from given preorder and postorder traversals
Given two arrays that represent preorder and postorder traversals of a full binary tree, construct the binary tree. Full Binary Tree is a binary tree where every node has either 0 or 2 children. Illustration: Following are examples of Full Trees. 1 / \ 2 3 / \ / \ 4 5 6 7 1 / \ 2 3 / \ 4 5 / \ 6 7 1 / \ 2 3 / \ / \ 4 5 6 7 / \ 8 9 It is not possibl
14 min read
Check if given inorder and preorder traversals are valid for any Binary Tree without building the tree
cGiven two arrays pre[] and in[] representing the preorder and inorder traversal of the binary tree, the task is to check if the given traversals are valid for any binary tree or not without building the tree. If it is possible, then print Yes. Otherwise, print No. Examples: Input: pre[] = {1, 2, 4, 5, 7, 3, 6, 8}, in[] = {4, 2, 5, 7, 1, 6, 8, 3}Ou
15+ min read
Construct the full k-ary tree from its preorder traversal
Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children. Examples: Input : preorder[] = {1, 2, 5, 6, 7, 3, 8, 9, 10, 4} k = 3 Output : Postorder traversal of constructed full k-ary tree is: 5 6
10 min read
Leaf nodes from Preorder of a Binary Search Tree (Using Recursion)
Given Preorder traversal of a Binary Search Tree. Then the task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples : Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4 In this post, a simple recursive sol
5 min read
Modify a binary tree to get preorder traversal using right pointers only
Given a binary tree. Modify it in such a way that after modification you can have a preorder traversal of it using only the right pointers. During modification, you can use right as well as left pointers. Examples: Input : 10 / \ 8 2 / \ 3 5 Output : 10 \ 8 \ 3 \ 5 \ 2 Explanation : The preorder traversal of given binary tree is 10 8 3 5 2. Method
15 min read
Find n-th node in Preorder traversal of a Binary Tree
Given a Binary tree and a number N, write a program to find the N-th node in the Preorder traversal of the given Binary tree. Prerequisite: Tree Traversal Examples: Input: N = 4 11 / \ 21 31 / \ 41 51 Output: 51 Explanation: Preorder Traversal of given Binary Tree is 11 21 41 51 31, so 4th node will be 51. Input: N = 5 25 / \ 20 30 / \ / \ 18 22 24
6 min read
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal. Examples: Input: Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1 Input: Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order tr
13 min read
Modify Binary Tree by replacing each node with the sum of its Preorder Predecessor and Successor
Given a binary tree consisting of N nodes, the task is to replace each node in the binary tree with the sum of its preorder predecessor and preorder successor. Examples: Input: 2 / \ 3 4 / \ / \ 6 5 7 8 Output: 3 / \ 8 12 / \ / \ 8 10 12 7 Explanation: For Node 2: Preorder predecessor = 0 (as preorder predecessor is not present), preorder successor
13 min read
Construct a Perfect Binary Tree from Preorder Traversal
Given an array pre[], representing the Preorder traversal of a Perfect Binary Tree consisting of N nodes, the task is to construct a Perfect Binary Tree from the given Preorder Traversal and return the root of the tree. Examples: Input: pre[] = {1, 2, 4, 5, 3, 6, 7}Output: 1 / \ / \ 2 3 / \ / \ / \ / \ 4 5 6 7 Input: pre[] = {1, 2, 3}Output: 1 / \
11 min read
Check if a given array can represent Preorder Traversal of Binary Search Tree
Given an array of numbers, return true if given array can represent preorder traversal of a Binary Search Tree, else return false. Expected time complexity is O(n). Examples: Input: pre[] = {2, 4, 3} Output: true Given array can represent preorder traversal of below tree 2 \ 4 / 3 Input: pre[] = {2, 4, 1} Output: false Given array cannot represent
15 min read
Preorder predecessor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find Preorder predecessor of the given node. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15Input: 4Output: 10Preorder traversal of given tree is 20, 10, 4, 18, 14, 13, 15, 19, 26, 24, 27.Input: 19Output: 15A simple solution is to first store Preorde
8 min read
Leaf nodes from Preorder of a Binary Search Tree
Given a Preorder traversal of a Binary Search Tree. The task is to print leaf nodes of the Binary Search Tree from the given preorder. Examples: Input : preorder[] = {890, 325, 290, 530, 965}; Output : 290 530 965 Explanation : Tree represented is, 890 / \ 325 965 / \ 290 530 Input : preorder[] = { 3, 2, 4 }; Output : 2 4Recommended PracticePrint l
15 min read
Preorder Successor of a Node in Binary Tree
Given a binary tree and a node in the binary tree, find the preorder successor of the given node. It may be assumed that every node has a parent link. Examples: Consider the following binary tree 20 / \ 10 26 / \ / \ 4 18 24 27 / \ 14 19 / \ 13 15 Input : 4 Output : 18 Preorder traversal of given tree is 20, 10, 4, 18, 14, 13, 15, 19, 26, 24, 27. I
9 min read
Vertical Traversal of a Binary Tree using Preorder
Given a binary tree, print it vertically. The following examples illustrate the vertical order traversal.   Input:         1                  /    \                 2      3               / \   /   \             4   5  6   7                         /  \                        8    9  Output:  421 5 63 879 Brute Force Approach : O(n^2)We traverse th
15 min read
Binary Search Tree (BST) Traversals – Inorder, Preorder, Post Order
Given a Binary Search Tree, The task is to print the elements in inorder, preorder, and postorder traversal of the Binary Search Tree.  Input:  Output: Inorder Traversal: 10 20 30 100 150 200 300Preorder Traversal: 100 20 10 30 200 150 300Postorder Traversal: 10 30 20 150 300 200 100 Input:  Output: Inorder Traversal: 8 12 20 22 25 30 40Preorder Tr
11 min read
Preorder Traversal of Binary Tree
Preorder traversal is defined as a type of tree traversal that follows the Root-Left-Right policy where: The root node of the subtree is visited first.Then the left subtree is traversed.At last, the right subtree is traversed.Algorithm for Preorder Traversal of Binary TreeThe algorithm for preorder traversal is shown as follows: Preorder(root): If
7 min read
Check whether a binary tree is a full binary tree or not | Iterative Approach
Given a binary tree containing n nodes. The problem is to check whether the given binary tree is a full binary tree or not. A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has only one child node. Examples: Input : 1 / \ 2 3 / \ 4 5 Outp
8 min read
Check whether a binary tree is a full binary tree or not
A full binary tree is defined as a binary tree in which all nodes have either zero or two child nodes. Conversely, there is no node in a full binary tree, which has one child node. More information about full binary trees can be found here. For Example : Recommended PracticeFull binary treeTry It! To check whether a binary tree is a full binary tre
14 min read
Find Minimum Depth of a Binary Tree
Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Binary Tree is also 2. 10 / 5 Recommended PracticeMi
15 min read
Replace node with depth in a binary tree
Given a binary tree, replace each node with its depth value. For example, consider the following tree. Root is at depth 0, change its value to 0 and next level nodes are at depth 1 and so on. 3 0 / \ / \ 2 5 == >; 1 1 / \ / \ 1 4 2 2 The idea is to traverse tree starting from root. While traversing pass depth of node as parameter. We can track d
11 min read
Sum of nodes at maximum depth of a Binary Tree
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7 Input : root(of above tree) Output : 22 Explanation: Nodes at maximum depth are: 4, 5, 6, 7. So, sum of these nodes = 22 While traversing the nodes compare the level of the node with max_level (Maximum level
15+ min read
Depth of the deepest odd level node in Binary Tree
Given a Binary tree, find out depth of the deepest odd level leaf node. Take root level as depth 1. Examples:  Input : Output : 5Input : 10 / \ 28 13 / \ 14 15 / \ 23 24Output : 3We can traverse the tree starting from the root level and keep curr_level of the node. Increment the curr_level each time we go to left or a right subtree. Return the max
14 min read
Height and Depth of a node in a Binary Tree
Given a Binary Tree consisting of N nodes and a integer K, the task is to find the depth and height of the node with value K in the Binary Tree. The depth of a node is the number of edges present in path from the root node of a tree to that node.The height of a node is the number of edges present in the longest path connecting that node to a leaf n
15+ min read
Sum of nodes at maximum depth of a Binary Tree | Iterative Approach
Given a root node to a tree, find the sum of all the leaf nodes which are at maximum depth from the root node. Example: 1 / \ 2 3 / \ / \ 4 5 6 7Input : root(of above tree)Output : 22Explanation:Nodes at maximum depth are 4, 5, 6, 7. So, the sum of these nodes = 22Approach: There exists a recursive approach to this problem. This can also be solved
8 min read
Maximum Depth or Height of Binary Tree
Given a binary tree, the task is to find the maximum depth or height of the tree. The height of the tree is the number of vertices in the tree from the root to the deepest node. Examples: Example 1: The height of the below binary tree is 3. Example 2: The height of the below binary tree is 4 Table of Content [Expected Approach - 1] Using Recursion
15+ min read
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Preorder Traversal of N-ary Tree Without Recursion
Given an n-ary tree, print preorder traversal of it. Example : Preorder traversal of below tree is A B K N M J F D G E C H I L The idea is to use stack like iterative preorder traversal of binary tree. Create an empty stack to store nodes. Push the root node to the stack. Run a loop while the stack is not empty Pop the top node from stack. Print th
7 min read
Construct a special tree from given preorder traversal
Given an array 'pre[]' that represents Preorder traversal of a special binary tree where every node has either 0 or 2 children. One more array 'preLN[]' is given which has only two possible values 'L' and 'N'. The value 'L' in 'preLN[]' indicates that the corresponding node in Binary Tree is a leaf node and value 'N' indicates that the correspondin
15+ min read
Article Tags :
Practice Tags :