Diameter of binary tree in C++In this article, you will learn about the diameter of binary trees in C++ with examples. The number of edges that connect the longest paths between any two nodes in a binary tree allows us to calculate the diameter of a binary tree. The diameter of the binary tree is a measure commonly used to describe its breadth. The path taken is dependent upon the binary tree's diameter and may or may not traverse the binary tree's root. There are two leaf nodes in the path, each of whose diameter can be calculated. There are two possibilities for determining the longest path among two nodes expressing the binary tree's diameter:
Approach 1:The measurement of the diameter of a tree T is the greatest of the following:
Filename: DiameterOfbtree.cpp Output: The diameter is 4 Approach 2:Efficient Approach: You can use the below approach to solve the problem: The above implementation can be improved by computing the height within the same iteration rather than calling heightoftree() function independently. Output: The diameter of the given binary tree is 4 Approach 3: Using the Morris Traversal AlgorithmThe Morris Traversal Algorithm modifies the binary tree's structure by linking the left subtree's rightmost node to its parent. It allows you to navigate the tree without taking up extra space for the stack or recursive function. To put the above idea into implementation, follow the steps below:
Filename: Morris_Traversal.cpp Output: The diameter is 4 Complexities: Time complexity: O(N), where N denotes the total number of nodes in a binary tree. Space Complexity: O(h), Morris Traversal has an auxiliary space complexity of O(1) because it doesn't use additional information structures like stacks or queues. On the other hand, the recursive stack of a program increases the space complexity, resulting in O(h), where h is the binary tree's height. Next TopicFoldable binary tree in C++ |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India