 GeeksforGeeks App
Open App Browser
Continue

# Find the Maximum Depth or Height of given Binary Tree

Given a binary tree, the task is to find the height of the tree. The height of the tree is the number of edges in the tree from the root to the deepest node.

Note: The height of an empty tree is 0. Example of Binary Tree

Recommended Practice

Recursively calculate the height of the left and the right subtrees of a node and assign height to the node as max of the heights of two children plus 1. See below the pseudo code and program for details.

Illustration:

Consider the following tree: Example of Tree

maxDepth(‘1’) = max(maxDepth(‘2’), maxDepth(‘3’)) + 1 = 2 + 1

because recursively
maxDepth(‘2’) =  max (maxDepth(‘4’), maxDepth(‘5’)) + 1 = 1 + 1 and  (as height of both ‘4’ and ‘5’ are 1)
maxDepth(‘3’) = 1

Follow the below steps to Implement the idea:

• Recursively do a Depth-first search.
• If the tree is empty then return 0
• Otherwise, do the following
• Get the max depth of the left subtree recursively  i.e. call maxDepth( tree->left-subtree)
• Get the max depth of the right subtree recursively  i.e. call maxDepth( tree->right-subtree)
• Get the max of max depths of left and right subtrees and add 1 to it for the current node.
• • Return max_depth.

Below is the Implementation of the above approach:

## C++

 `// C++ program to find height of tree``#include ``using` `namespace` `std;` `/* A binary tree node has data, pointer to left child``and a pointer to right child */``class` `node {``public``:``    ``int` `data;``    ``node* left;``    ``node* right;``};` `/* Compute the "maxDepth" of a tree -- the number of``    ``nodes along the longest path from the root node``    ``down to the farthest leaf node.*/``int` `maxDepth(node* node)``{``    ``if` `(node == NULL)``        ``return` `0;``    ``else` `{``        ``/* compute the depth of each subtree */``        ``int` `lDepth = maxDepth(node->left);``        ``int` `rDepth = maxDepth(node->right);` `        ``/* use the larger one */``        ``if` `(lDepth > rDepth)``            ``return` `(lDepth + 1);``        ``else``            ``return` `(rDepth + 1);``    ``}``}` `/* Helper function that allocates a new node with the``given data and NULL left and right pointers. */``node* newNode(``int` `data)``{``    ``node* Node = ``new` `node();``    ``Node->data = data;``    ``Node->left = NULL;``    ``Node->right = NULL;` `    ``return` `(Node);``}` `// Driver code``int` `main()``{``    ``node* root = newNode(1);` `    ``root->left = newNode(2);``    ``root->right = newNode(3);``    ``root->left->left = newNode(4);``    ``root->left->right = newNode(5);` `    ``cout << ``"Height of tree is "` `<< maxDepth(root);``    ``return` `0;``}` `// This code is contributed by Amit Srivastav`

## C

 `#include ``#include ` `/* A binary tree node has data, pointer to left child``   ``and a pointer to right child */``struct` `node {``    ``int` `data;``    ``struct` `node* left;``    ``struct` `node* right;``};` `/* Compute the "maxDepth" of a tree -- the number of``    ``nodes along the longest path from the root node``    ``down to the farthest leaf node.*/``int` `maxDepth(``struct` `node* node)``{``    ``if` `(node == NULL)``        ``return` `0;``    ``else` `{``        ``/* compute the depth of each subtree */``        ``int` `lDepth = maxDepth(node->left);``        ``int` `rDepth = maxDepth(node->right);` `        ``/* use the larger one */``        ``if` `(lDepth > rDepth)``            ``return` `(lDepth + 1);``        ``else``            ``return` `(rDepth + 1);``    ``}``}` `/* Helper function that allocates a new node with the``   ``given data and NULL left and right pointers. */``struct` `node* newNode(``int` `data)``{``    ``struct` `node* node``        ``= (``struct` `node*)``malloc``(``sizeof``(``struct` `node));``    ``node->data = data;``    ``node->left = NULL;``    ``node->right = NULL;` `    ``return` `(node);``}` `int` `main()``{``    ``struct` `node* root = newNode(1);` `    ``root->left = newNode(2);``    ``root->right = newNode(3);``    ``root->left->left = newNode(4);``    ``root->left->right = newNode(5);` `    ``printf``(``"Height of tree is %d"``, maxDepth(root));` `    ``getchar``();``    ``return` `0;``}`

## Java

 `// Java program to find height of tree` `// A binary tree node``class` `Node {``    ``int` `data;``    ``Node left, right;` `    ``Node(``int` `item)``    ``{``        ``data = item;``        ``left = right = ``null``;``    ``}``}` `class` `BinaryTree {``    ``Node root;` `    ``/* Compute the "maxDepth" of a tree -- the number of``       ``nodes along the longest path from the root node``       ``down to the farthest leaf node.*/``    ``int` `maxDepth(Node node)``    ``{``        ``if` `(node == ``null``)``            ``return` `0``;``        ``else` `{``            ``/* compute the depth of each subtree */``            ``int` `lDepth = maxDepth(node.left);``            ``int` `rDepth = maxDepth(node.right);` `            ``/* use the larger one */``            ``if` `(lDepth > rDepth)``                ``return` `(lDepth + ``1``);``            ``else``                ``return` `(rDepth + ``1``);``        ``}``    ``}` `    ``/* Driver program to test above functions */``    ``public` `static` `void` `main(String[] args)``    ``{``        ``BinaryTree tree = ``new` `BinaryTree();` `        ``tree.root = ``new` `Node(``1``);``        ``tree.root.left = ``new` `Node(``2``);``        ``tree.root.right = ``new` `Node(``3``);``        ``tree.root.left.left = ``new` `Node(``4``);``        ``tree.root.left.right = ``new` `Node(``5``);` `        ``System.out.println(``"Height of tree is "``                           ``+ tree.maxDepth(tree.root));``    ``}``}` `// This code has been contributed by Amit Srivastav`

## Python3

 `# Python3 program to find the maximum depth of tree` `# A binary tree node`  `class` `Node:` `    ``# Constructor to create a new node``    ``def` `__init__(``self``, data):``        ``self``.data ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None` `# Compute the "maxDepth" of a tree -- the number of nodes``# along the longest path from the root node down to the``# farthest leaf node`  `def` `maxDepth(node):``    ``if` `node ``is` `None``:``        ``return` `0` `    ``else``:` `        ``# Compute the depth of each subtree``        ``lDepth ``=` `maxDepth(node.left)``        ``rDepth ``=` `maxDepth(node.right)` `        ``# Use the larger one``        ``if` `(lDepth > rDepth):``            ``return` `lDepth``+``1``        ``else``:``            ``return` `rDepth``+``1`  `# Driver program to test above function``root ``=` `Node(``1``)``root.left ``=` `Node(``2``)``root.right ``=` `Node(``3``)``root.left.left ``=` `Node(``4``)``root.left.right ``=` `Node(``5``)`  `print``(``"Height of tree is %d"` `%` `(maxDepth(root)))` `# This code is contributed by Amit Srivastav`

## C#

 `// C# program to find height of tree``using` `System;` `// A binary tree node``public` `class` `Node {``    ``public` `int` `data;``    ``public` `Node left, right;` `    ``public` `Node(``int` `item)``    ``{``        ``data = item;``        ``left = right = ``null``;``    ``}``}` `public` `class` `BinaryTree {``    ``Node root;` `    ``/* Compute the "maxDepth" of a tree -- the number of``    ``nodes along the longest path from the root node``    ``down to the farthest leaf node.*/``    ``int` `maxDepth(Node node)``    ``{``        ``if` `(node == ``null``)``            ``return` `0;``        ``else` `{``            ``/* compute the depth of each subtree */``            ``int` `lDepth = maxDepth(node.left);``            ``int` `rDepth = maxDepth(node.right);` `            ``/* use the larger one */``            ``if` `(lDepth > rDepth)``                ``return` `(lDepth + 1);``            ``else``                ``return` `(rDepth + 1);``        ``}``    ``}` `    ``/* Driver code */``    ``public` `static` `void` `Main(String[] args)``    ``{``        ``BinaryTree tree = ``new` `BinaryTree();` `        ``tree.root = ``new` `Node(1);``        ``tree.root.left = ``new` `Node(2);``        ``tree.root.right = ``new` `Node(3);``        ``tree.root.left.left = ``new` `Node(4);``        ``tree.root.left.right = ``new` `Node(5);` `        ``Console.WriteLine(``"Height of tree is "``                          ``+ tree.maxDepth(tree.root));``    ``}``}` `// This code has been contributed by``// Correction done by Amit Srivastav`

## Javascript

 ``

Output

`Height of tree is 3`

Time Complexity: O(N) (Please see the post on Tree Traversal for details)
Auxiliary Space: O(N) due to recursive stack.

## Find the Maximum Depth or Height of a Tree using Level Order Traversal:

Do Level Order Traversal, while adding Nodes at each level to Queue, we have to add NULL Node so that whenever it is encountered, we can increment the value of variable and that level get counted.

Follow the below steps to Implement the idea:

• Traverse the tree in level order traversal starting from root.
• Initialize an empty queue Q, a variable depth and push root, then push null into the Q.
• Run a while loop till Q is not empty.
• Store the front element of Q and Pop out the front element.
• If the front of Q is NULL then increment depth by one and if queue is not empty then push NULL into the Q.
• Else if the element is not NULL then check for its left and right children and if they are not NULL push them into Q.
• Return depth.

Below is the Implementation of the above approach:

## C++

 `#include ``#include ``using` `namespace` `std;` `// A Tree node``struct` `Node {``    ``int` `key;``    ``struct` `Node *left, *right;``};` `// Utility function to create a new node``Node* newNode(``int` `key)``{``    ``Node* temp = ``new` `Node;``    ``temp->key = key;``    ``temp->left = temp->right = NULL;``    ``return` `(temp);``}` `/*Function to find the height(depth) of the tree*/``int` `height(``struct` `Node* root)``{` `    ``// Initialising a variable to count the``    ``// height of tree``    ``int` `depth = 0;` `    ``queue q;` `    ``// Pushing first level element along with NULL``    ``q.push(root);``    ``q.push(NULL);``    ``while` `(!q.empty()) {``        ``Node* temp = q.front();``        ``q.pop();` `        ``// When NULL encountered, increment the value``        ``if` `(temp == NULL) {``            ``depth++;``        ``}` `        ``// If NULL not encountered, keep moving``        ``if` `(temp != NULL) {``            ``if` `(temp->left) {``                ``q.push(temp->left);``            ``}``            ``if` `(temp->right) {``                ``q.push(temp->right);``            ``}``        ``}` `        ``// If queue still have elements left,``        ``// push NULL again to the queue.``        ``else` `if` `(!q.empty()) {``            ``q.push(NULL);``        ``}``    ``}``    ``return` `depth;``}` `// Driver program``int` `main()``{``    ``// Let us create Binary Tree shown in above example``    ``Node* root = newNode(1);``    ``root->left = newNode(2);``    ``root->right = newNode(3);` `    ``root->left->left = newNode(4);``    ``root->left->right = newNode(5);` `    ``cout << ``"Height(Depth) of tree is: "` `<< height(root);``}`

## Java

 `// Java program for above approach``import` `java.util.LinkedList;``import` `java.util.Queue;` `class` `GFG {` `    ``// A tree node structure``    ``static` `class` `Node {``        ``int` `key;``        ``Node left;``        ``Node right;``    ``}` `    ``// Utility function to create``    ``// a new node``    ``static` `Node newNode(``int` `key)``    ``{``        ``Node temp = ``new` `Node();``        ``temp.key = key;``        ``temp.left = temp.right = ``null``;``        ``return` `temp;``    ``}` `    ``/*Function to find the height(depth) of the tree*/``    ``public` `static` `int` `height(Node root)``    ``{` `        ``// Initialising a variable to count the``        ``// height of tree``        ``int` `depth = ``0``;` `        ``Queue q = ``new` `LinkedList<>();` `        ``// Pushing first level element along with null``        ``q.add(root);``        ``q.add(``null``);``        ``while` `(!q.isEmpty()) {``            ``Node temp = q.peek();``            ``q.remove();` `            ``// When null encountered, increment the value``            ``if` `(temp == ``null``) {``                ``depth++;``            ``}` `            ``// If null not encountered, keep moving``            ``if` `(temp != ``null``) {``                ``if` `(temp.left != ``null``) {``                    ``q.add(temp.left);``                ``}``                ``if` `(temp.right != ``null``) {``                    ``q.add(temp.right);``                ``}``            ``}` `            ``// If queue still have elements left,``            ``// push null again to the queue.``            ``else` `if` `(!q.isEmpty()) {``                ``q.add(``null``);``            ``}``        ``}``        ``return` `depth;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String args[])``    ``{``        ``Node root = newNode(``1``);``        ``root.left = newNode(``2``);``        ``root.right = newNode(``3``);` `        ``root.left.left = newNode(``4``);``        ``root.left.right = newNode(``5``);` `        ``System.out.println(``"Height(Depth) of tree is: "``                           ``+ height(root));``    ``}``}` `// This code is contributed by jana_sayantan.`

## Python3

 `# Python code to implement the approach` `# A Tree node`  `class` `Node:` `    ``def` `__init__(``self``):``        ``self``.key ``=` `0``        ``self``.left, ``self``.right ``=` `None``, ``None` `# Utility function to create a new node`  `def` `newNode(key):` `    ``temp ``=` `Node()``    ``temp.key ``=` `key``    ``temp.left, temp.right ``=` `None``, ``None``    ``return` `temp`  `# Function to find the height(depth) of the tree``def` `height(root):` `    ``# Initialising a variable to count the``    ``# height of tree``    ``depth ``=` `0` `    ``q ``=` `[]` `    ``# appending first level element along with None``    ``q.append(root)``    ``q.append(``None``)``    ``while``(``len``(q) > ``0``):``        ``temp ``=` `q[``0``]``        ``q ``=` `q[``1``:]` `        ``# When None encountered, increment the value``        ``if``(temp ``=``=` `None``):``            ``depth ``+``=` `1` `        ``# If None not encountered, keep moving``        ``if``(temp !``=` `None``):``            ``if``(temp.left):``                ``q.append(temp.left)` `            ``if``(temp.right):``                ``q.append(temp.right)` `        ``# If queue still have elements left,``        ``# append None again to the queue.``        ``elif``(``len``(q) > ``0``):``            ``q.append(``None``)``    ``return` `depth` `# Driver program`  `# Let us create Binary Tree shown in above example``root ``=` `newNode(``1``)``root.left ``=` `newNode(``2``)``root.right ``=` `newNode(``3``)` `root.left.left ``=` `newNode(``4``)``root.left.right ``=` `newNode(``5``)` `print``(f``"Height(Depth) of tree is: {height(root)}"``)`  `# This code is contributed by shinjanpatra`

## C#

 `// C# Program to find the Maximum Depth or Height of Binary Tree``using` `System;``using` `System.Collections.Generic;` `// A Tree node``public` `class` `Node {``    ``public` `int` `data;``    ``public` `Node left, right;` `    ``public` `Node(``int` `item)``    ``{``        ``data = item;``        ``left = ``null``;``        ``right = ``null``;``    ``}``}` `public` `class` `BinaryTree {` `    ``Node root;` `    ``// Function to find the height(depth) of the tree``    ``int` `height()``    ``{``        ``// Initialising a variable to count the``        ``// height of tree``        ``int` `depth = 0;` `        ``Queue q = ``new` `Queue();` `        ``// Pushing first level element along with NULL``        ``q.Enqueue(root);``        ``q.Enqueue(``null``);``        ``while` `(q.Count != 0) {``            ``Node temp = q.Dequeue();` `            ``// When NULL encountered, increment the value``            ``if` `(temp == ``null``)``                ``depth++;` `            ``// If NULL  not encountered, keep moving``            ``if` `(temp != ``null``) {``                ``if` `(temp.left != ``null``) {``                    ``q.Enqueue(temp.left);``                ``}``                ``if` `(temp.right != ``null``) {``                    ``q.Enqueue(temp.right);``                ``}``            ``}` `            ``// If queue still have elements left,``            ``// push NULL again to the queue``            ``else` `if` `(q.Count != 0) {``                ``q.Enqueue(``null``);``            ``}``        ``}``        ``return` `depth;``    ``}` `    ``// Driver program``    ``public` `static` `void` `Main()``    ``{``        ``// Let us create Binary Tree shown in above example``        ``BinaryTree tree = ``new` `BinaryTree();``        ``tree.root = ``new` `Node(1);``        ``tree.root.left = ``new` `Node(2);``        ``tree.root.right = ``new` `Node(3);``        ``tree.root.left.left = ``new` `Node(4);``        ``tree.root.left.right = ``new` `Node(5);` `        ``Console.WriteLine(``"Height(Depth) of tree is: "``                          ``+ tree.height());``    ``}``}` `// This code is contributed by Yash Agarwal(yashagarwal2852002)`

## Javascript

 ``

Output

`Height(Depth) of tree is: 3`

Time Complexity: O(N)
Auxiliary Space: O(N)

### Another method to find height using Level Order Traversal:

This method also uses the concept of Level Order Traversal but we wont be adding null in the Queue. Simply increase the counter when the level increases and push the children of current node into the queue, then remove all the nodes from the queue of the current Level.

## C++

 `// C++ program for above approach``#include ``using` `namespace` `std;` `// A Tree node``struct` `Node {``  ``int` `key;``  ``struct` `Node *left, *right;``};` `// Utility function to create a new node``Node* newNode(``int` `key)``{``  ``Node* temp = ``new` `Node;``  ``temp->key = key;``  ``temp->left = temp->right = NULL;``  ``return` `(temp);``}` `/*Function to find the height(depth) of the tree*/``int` `height(Node* root)``{` `  ``// Initialising a variable to count the``  ``// height of tree``  ``queue q;``  ``q.push(root);``  ``int` `height = 0;``  ``while` `(!q.empty()) {``    ``int` `size = q.size();``    ``for` `(``int` `i = 0; i < size; i++) {``      ``Node* temp = q.front();``      ``q.pop();``      ``if` `(temp->left != NULL) {``        ``q.push(temp->left);``      ``}``      ``if` `(temp->right != NULL) {``        ``q.push(temp->right);``      ``}``    ``}``    ``height++;``  ``}``  ``return` `height;``}` `// Driver program``int` `main()``{` `  ``// Let us create Binary Tree shown in above example``  ``Node* root = newNode(1);``  ``root->left = newNode(2);``  ``root->right = newNode(3);` `  ``root->left->left = newNode(4);``  ``root->left->right = newNode(5);` `  ``cout << ``"Height(Depth) of tree is: "` `<< height(root);``}` `// This code is contributed by Abhijeet Kumar(abhijeet19403)`

## Java

 `// Java program for above approach``import` `java.util.LinkedList;``import` `java.util.Queue;` `class` `GFG {` `    ``// A tree node structure``    ``static` `class` `Node {``        ``int` `key;``        ``Node left;``        ``Node right;``    ``}` `    ``// Utility function to create``    ``// a new node``    ``static` `Node newNode(``int` `key)``    ``{``        ``Node temp = ``new` `Node();``        ``temp.key = key;``        ``temp.left = temp.right = ``null``;``        ``return` `temp;``    ``}` `    ``/*Function to find the height(depth) of the tree*/``    ``public` `static` `int` `height(Node root)``    ``{` `        ``// Initialising a variable to count the``        ``// height of tree``        ``Queue q = ``new` `LinkedList();``        ``q.add(root);``        ``int` `height = ``0``;``        ``while` `(!q.isEmpty()) {``            ``int` `size = q.size();``            ``for` `(``int` `i = ``0``; i < size; i++) {``                ``Node temp = q.poll();``                ``if` `(temp.left != ``null``) {``                    ``q.add(temp.left);``                ``}``                ``if` `(temp.right != ``null``) {``                    ``q.add(temp.right);``                ``}``            ``}``            ``height++;``        ``}``        ``return` `height;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String args[])``    ``{``        ``Node root = newNode(``1``);``        ``root.left = newNode(``2``);``        ``root.right = newNode(``3``);` `        ``root.left.left = newNode(``4``);``        ``root.left.right = newNode(``5``);` `        ``System.out.println(``"Height(Depth) of tree is: "``                           ``+ height(root));``    ``}``}`

## C#

 `using` `System;``using` `System.Collections.Generic;` `class` `GFG {` `  ``// A Tree node``  ``class` `Node {``    ``public` `int` `key;``    ``public` `Node left, right;` `    ``public` `Node(``int` `key)``    ``{``      ``this``.key=key;``      ``this``.left=``this``.right=``null``;``    ``}``  ``}` `  ``// Utility function to create a new node``  ``/*Node newNode(int key)``    ``{``      ``Node* temp = new Node;``      ``temp.key = key;``      ``temp.left = temp.right = NULL;``      ``return (temp);``    ``}*/` `  ``/*Function to find the height(depth) of the tree*/``  ``static` `int` `height(Node root)``  ``{` `    ``// Initialising a variable to count the``    ``// height of tree``    ``Queue q=``new` `Queue();``    ``q.Enqueue(root);``    ``int` `height = 0;``    ``while` `(q.Count>0) {``      ``int` `size = q.Count;``      ``for` `(``int` `i = 0; i < size; i++) {``        ``Node temp = q.Peek();``        ``q.Dequeue();``        ``if` `(temp.left != ``null``) {``          ``q.Enqueue(temp.left);``        ``}``        ``if` `(temp.right != ``null``) {``          ``q.Enqueue(temp.right);``        ``}``      ``}``      ``height++;``    ``}``    ``return` `height;``  ``}` `  ``// Driver program``  ``public` `static` `void` `Main()``  ``{` `    ``// Let us create Binary Tree shown in above example``    ``Node root = ``new` `Node(1);``    ``root.left = ``new` `Node(2);``    ``root.right = ``new` `Node(3);` `    ``root.left.left = ``new` `Node(4);``    ``root.left.right = ``new` `Node(5);` `    ``Console.Write(``"Height(Depth) of tree is: "` `+ height(root));``  ``}``}` `// This code is contributed by poojaagarwal2.`

## Python3

 `# Python3 program to find the height of a tree``  ` `# A binary tree node``class` `Node:``  ` `    ``# Constructor to create a new node``    ``def` `__init__(``self``, data):``        ``self``.key ``=` `data``        ``self``.left ``=` `None``        ``self``.right ``=` `None``  ` `# Function to find height of tree``def` `height(root):``    ``# Base Case``    ``if` `root ``is` `None``:``        ``return` `0``  ` `    ``# Create an empty queue for level order traversal``    ``q ``=` `[]``  ` `    ``# Enqueue Root and initialize height``    ``q.append(root)``    ``height ``=` `0``  ` `    ``# Loop while queue is not empty``    ``while` `q:``  ` `        ``# nodeCount (queue size) indicates number of nodes``        ``# at current level``        ``nodeCount ``=` `len``(q)``  ` `        ``# Dequeue all nodes of current level and Enqueue all``        ``# nodes of next level``        ``while` `nodeCount > ``0``:``            ``node ``=` `q.pop(``0``)``            ``if` `node.left ``is` `not` `None``:``                ``q.append(node.left)``            ``if` `node.right ``is` `not` `None``:``                ``q.append(node.right)``            ``nodeCount ``-``=` `1``        ``height ``+``=` `1``  ` `    ``return` `height``  ` `# Driver Code``root ``=` `Node(``1``)``root.left ``=` `Node(``2``)``root.right ``=` `Node(``3``)``root.left.left ``=` `Node(``4``)``root.left.right ``=` `Node(``5``)``  ` `print``(``"Height(Depth) of tree is"``, height(root))`

## Javascript

 `// JavaScript program for above approach``// a tree node``class Node{``    ``constructor(key){``        ``this``.key = key;``        ``this``.left = ``this``.right = ``null``;``    ``}  ``}` `// utility function to create a new node``function` `newNode(key){``    ``return` `new` `Node(key);``}` `// function to find the  height of the tree``function` `height(root){``    ``// initialising a variable to count the``    ``// height of tree``    ``let q = [];``    ``q.push(root);``    ``let height = 0;``    ``while``(q.length > 0){``        ``let size = q.length;``        ``for``(let i = 0; i

Output

`Height(Depth) of tree is: 3`

Time Complexity: O(N)
Auxiliary Space: O(N)

Finding height using Morris Traversal Algorithm:

The basic idea behind the algorithm is to traverse the left subtree of each node first and then move to its right subtree. During the traversal, we keep track of the maximum depth of the tree by incrementing a counter variable each time we move down a level in the tree.

Follow the below steps to implement the above idea:

• Initialize the current node as the root of the tree.
• While the current node is not NULL:
• If the left child of the current node is NULL, visit the current node and move to its right child.
• If the left child of the current node is not NULL:
• Find the rightmost node in the left subtree of the current node.
• If the right child of this node is NULL, set it to the current node and move to the left child of the current node.
• If the right child of this node is not NULL, set it back to NULL, visit the current node, and move to its right child.
• Return the maximum depth of the tree.

Below is the implementation of the above approach:

## C++

 `// C++ code to implement the above approach using morris``// traversal Algorithm``#include ``using` `namespace` `std;` `// Definition of a binary tree node``struct` `TreeNode {``    ``int` `val;``    ``TreeNode* left;``    ``TreeNode* right;``    ``TreeNode(``int` `x)``        ``: val(x)``        ``, left(NULL)``        ``, right(NULL)``    ``{``    ``}``};` `// Function to find the height of a binary tree using Morris``// Traversal technique``int` `findHeight(TreeNode* root)``{``    ``int` `height = 0;``    ``TreeNode* current = root;``    ``while` `(current != NULL) {``        ``if` `(current->left == NULL) {``            ``// If left subtree is NULL, move to right``            ``// subtree``            ``current = current->right;``            ``height++; ``// Increment the height of the tree``        ``}``        ``else` `{``            ``// Find the inorder predecessor of current node``            ``TreeNode* pre = current->left;``            ``while` `(pre->right != NULL``                   ``&& pre->right != current)``                ``pre = pre->right;` `            ``if` `(pre->right == NULL) {``                ``// Make current node the right child of its``                ``// inorder predecessor``                ``pre->right = current;``                ``current = current->left;``            ``}``            ``else` `{``                ``// If the right child of the inorder``                ``// predecessor already points to the current``                ``// node, then we have traversed the left``                ``// subtree and its inorder traversal is``                ``// complete.``                ``pre->right = NULL;``                ``current = current->right; ``// Move to the``                                          ``// right subtree``            ``}``        ``}``    ``}``    ``return` `height;``}` `// Driver Code``int` `main()``{``    ``// Create the binary tree``    ``TreeNode* root = ``new` `TreeNode(1);``    ``root->left = ``new` `TreeNode(2);``    ``root->right = ``new` `TreeNode(3);``    ``root->left->left = ``new` `TreeNode(4);``    ``root->left->right = ``new` `TreeNode(5);` `    ``// Calculate the height of the tree using Morris``    ``// Traversal``    ``int` `height = findHeight(root);` `    ``// Output the height of the tree``    ``cout << ``"Height of the binary tree is: "` `<< height``         ``<< endl;` `    ``return` `0;``}``// This Code is Contributed by Veerendra_Singh_Rajpoot`

## Java

 `// Java code to implement the above approach using morris``// traversal Algorithm``import` `java.util.*;` `// Definition of a binary tree node``class` `TreeNode {``    ``int` `val;``    ``TreeNode left;``    ``TreeNode right;` `    ``TreeNode(``int` `x)``    ``{``        ``val = x;``        ``left = ``null``;``        ``right = ``null``;``    ``}``};` `public` `class` `Main {``    ``// Function to find the height of a binary tree using``    ``// Morris Traversal technique``    ``public` `static` `int` `findHeight(TreeNode root)``    ``{``        ``int` `height = ``0``;``        ``TreeNode current = root;``        ``while` `(current != ``null``) {``            ``if` `(current.left == ``null``) {``                ``// If left subtree is null, move to right``                ``// subtree``                ``current = current.right;``                ``height++; ``// Increment the height of the``                          ``// tree``            ``}``            ``else` `{``                ``// Find the inorder predecessor of current``                ``// node``                ``TreeNode pre = current.left;``                ``while` `(pre.right != ``null``                       ``&& pre.right != current)``                    ``pre = pre.right;` `                ``if` `(pre.right == ``null``) {``                    ``// Make current node the right child of``                    ``// its inorder predecessor``                    ``pre.right = current;``                    ``current = current.left;``                ``}``                ``else` `{``                    ``// If the right child of the inorder``                    ``// predecessor already points to the``                    ``// current node, then we have traversed``                    ``// the left subtree and its inorder``                    ``// traversal is complete.``                    ``pre.right = ``null``;``                    ``current``                        ``= current.right; ``// Move to the``                                         ``// right subtree``                ``}``            ``}``        ``}``        ``return` `height;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``        ``// Create the binary tree``        ``TreeNode root = ``new` `TreeNode(``1``);``        ``root.left = ``new` `TreeNode(``2``);``        ``root.right = ``new` `TreeNode(``3``);``        ``root.left.left = ``new` `TreeNode(``4``);``        ``root.left.right = ``new` `TreeNode(``5``);` `        ``// Calculate the height of the tree using Morris``        ``// Traversal``        ``int` `height = findHeight(root);` `        ``// Output the height of the tree``        ``System.out.println(``"Height of the binary tree is: "``                           ``+ height);``    ``}``}``// This Code is Contributed by rutikbhosale`

## Python3

 `# Python3 code to implement the above approach using morris``# traversal Algorithm`  `class` `TreeNode:``    ``def` `__init__(``self``, x):``        ``self``.val ``=` `x``        ``self``.left ``=` `None``        ``self``.right ``=` `None` `# Function to find the height of a binary tree using Morris``# Traversal technique`  `def` `findHeight(root):``    ``height ``=` `0``    ``current ``=` `root``    ``while` `current !``=` `None``:``        ``if` `current.left ``=``=` `None``:``            ``# If left subtree is NULL, move to right``            ``# subtree``            ``current ``=` `current.right``            ``height ``+``=` `1`  `# Increment the height of the tree``        ``else``:``            ``# Find the inorder predecessor of current node``            ``pre ``=` `current.left``            ``while` `pre.right !``=` `None` `and` `pre.right !``=` `current:``                ``pre ``=` `pre.right` `            ``if` `pre.right ``=``=` `None``:``                ``# Make current node the right child of its``                ``# inorder predecessor``                ``pre.right ``=` `current``                ``current ``=` `current.left``            ``else``:``                ``# If the right child of the inorder``                ``# predecessor already points to the current``                ``# node, then we have traversed the left``                ``# subtree and its inorder traversal is``                ``# complete.``                ``pre.right ``=` `None``                ``current ``=` `current.right  ``# Move to the``                ``# right subtree``    ``return` `height`  `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ``# Create the binary tree``    ``root ``=` `TreeNode(``1``)``    ``root.left ``=` `TreeNode(``2``)``    ``root.right ``=` `TreeNode(``3``)``    ``root.left.left ``=` `TreeNode(``4``)``    ``root.left.right ``=` `TreeNode(``5``)` `    ``# Calculate the height of the tree using Morris``    ``# Traversal technique``    ``print``(``"Height of the binary tree is:"``, findHeight(root))`

## Javascript

 `// Definition of a binary tree node``class TreeNode {``    ``constructor(x) {``        ``this``.val = x;``        ``this``.left = ``null``;``        ``this``.right = ``null``;``    ``}``}` `// Function to find the height of``// a binary tree using Morris Traversal technique``function` `findHeight(root) {``    ``let height = 0;``    ``let current = root;``    ``while` `(current != ``null``)``    ``{``        ``if` `(current.left == ``null``)``        ``{``        ` `            ``// If left subtree is NULL, move to right subtree``            ``current = current.right;``            ``height++; ``// Increment the height of the tree``        ``}``        ``else``        ``{``        ` `            ``// Find the inorder predecessor of current node``            ``let pre = current.left;``            ``while` `(pre.right != ``null` `&& pre.right != current)``                ``pre = pre.right;` `            ``if` `(pre.right == ``null``)``            ``{``            ` `                ``// Make current node the right child of its inorder predecessor``                ``pre.right = current;``                ``current = current.left;``            ``}``            ``else``            ``{``            ` `                ``// If the right child of the inorder predecessor``                ``// already points to the current node,``                ``// then we have traversed the left subtree and``                ``// its inorder traversal is complete.``                ``pre.right = ``null``;``                ``current = current.right; ``// Move to the right subtree``            ``}``        ``}``    ``}``    ``return` `height;``}` `// Driver Code` `// Create the binary tree``let root = ``new` `TreeNode(1);``root.left = ``new` `TreeNode(2);``root.right = ``new` `TreeNode(3);``root.left.left = ``new` `TreeNode(4);``root.left.right = ``new` `TreeNode(5);` `// Calculate the height of the tree using Morris Traversal``let height = findHeight(root);``console.log(``"Height of the binary tree is: "` `+ height);`

## C#

 `// C# code to implement the above approach using morris``// traversal Algorithm``using` `System;` `// Definition of a binary tree node``public` `class` `TreeNode {``    ``public` `int` `val;``    ``public` `TreeNode left;``    ``public` `TreeNode right;``    ``public` `TreeNode(``int` `x)``    ``{``        ``val = x;``        ``left = ``null``;``        ``right = ``null``;``    ``}``}` `public` `class` `Program {``    ``// Function to find the height of a binary tree using``    ``// Morris Traversal technique``    ``public` `static` `int` `FindHeight(TreeNode root)``    ``{``        ``int` `height = 0;``        ``TreeNode current = root;``        ``while` `(current != ``null``) {``            ``if` `(current.left == ``null``) {``                ``// If left subtree is null, move to right``                ``// subtree``                ``current = current.right;``                ``height++; ``// Increment the height of the``                ``// tree``            ``}``            ``else` `{``                ``// Find the inorder predecessor of current``                ``// node``                ``TreeNode pre = current.left;``                ``while` `(pre.right != ``null``                       ``&& pre.right != current)``                    ``pre = pre.right;``                ``if` `(pre.right == ``null``) {``                    ``// Make current node the right child of``                    ``// its inorder predecessor``                    ``pre.right = current;``                    ``current = current.left;``                ``}``                ``else` `{``                    ``// If the right child of the inorder``                    ``// predecessor already points to the``                    ``// current node, then we have traversed``                    ``// the left subtree and its inorder``                    ``// traversal is complete.``                    ``pre.right = ``null``;``                    ``current``                        ``= current.right; ``// Move to the``                                         ``// right subtree``                ``}``            ``}``        ``}``        ``return` `height;``    ``}` `    ``// Driver Code``    ``public` `static` `void` `Main()``    ``{``        ``// Create the binary tree``        ``TreeNode root = ``new` `TreeNode(1);``        ``root.left = ``new` `TreeNode(2);``        ``root.right = ``new` `TreeNode(3);``        ``root.left.left = ``new` `TreeNode(4);``        ``root.left.right = ``new` `TreeNode(5);` `        ``// Calculate the height of the tree using Morris``        ``// Traversal``        ``int` `height = FindHeight(root);` `        ``// Output the height of the tree``        ``Console.WriteLine(``"Height of the binary tree is: "``                          ``+ height);``    ``}``}`

Output

`Height of the binary tree is: 3`

Time Complexity: O(N), The time complexity of finding the height of a binary tree using Morris traversal is O(n), where n is the number of nodes in the tree.

Auxiliary Space: O(1), The space complexity of the algorithm is O(1), which is constant space complexity. This is because we are not using any additional data structures to store nodes or keep track of the traversal

My Personal Notes arrow_drop_up