![]() |
VOOZH | about |
Given a Binary tree, the task is to find the vertical width of the Binary tree. The width of a binary tree is the number of vertical paths in the Binary tree.
Examples:
Input:
Output: 6
Explanation: In this image, the tree contains 6 vertical lines which are the required width of the tree.Input :
7
/ \
6 5
/ \ / \
4 3 2 1
Output : 5
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
\ \
8 9
Output : 6
Approach:
Take inorder traversal and then take a temp variable to keep the track of unique vertical paths. when moving to left of the node then temp decreases by one and if goes to right then temp value increases by one. If the minimum is greater than temp, then update minimum = temp and if maximum less than temp then update maximum = temp. The vertical width of the tree will be equal to abs(minimum ) + maximum.
Follow the below steps to Implement the idea:
Below is the Implementation of the above approach:
5
Time Complexity: O(n)
Auxiliary Space: O(h) where h is the height of the binary tree. This much space is needed for recursive calls.
Below is the idea to solve the problem:
Create a class to store the node and the horizontal level of the node. The horizontal level of left node will be 1 less than its parent, and horizontal level of the right node will be 1 more than its parent. We create a minLevel variable to store the minimum horizontal level or the leftmost node in the tree, and a maxLevel variable to store the maximum horizontal level or the rightmost node in the tree. Traverse the tree in level order and store the minLevel and maxLevel. In the end, print sum of maxLevel and absolute value of minLevel which is the vertical width of the tree.
Follow the below steps to Implement the idea:
Below is the Implementation of the above approach:
5
Time Complexity: O(n). This much time is needed to traverse the tree.
Auxiliary Space: O(n). This much space is needed to maintain the queue.