Approach : Take inorder traversal and then take a temporary variable if we go left then temp value decreases and if go to right then temp value increases. Assert a condition in this, if the minimum is greater than temp, then minimum = temp and if maximum less then temp then maximum = temp. In the end, print minimum + maximum which is the vertical width of the tree.
C++
// CPP program to print vertical width
// of a tree
#include <bits/stdc++.h>
usingnamespacestd;
// A Binary Tree Node
structNode
{
intdata;
structNode *left, *right;
};
// get vertical width
voidlengthUtil(Node* root, int&maximum,
int&minimum, intcurr=0)
{
if(root == NULL)
return;
// traverse left
lengthUtil(root->left, maximum,
minimum, curr - 1);
// if curr is decrease then get
// value in minimum
if(minimum > curr)
minimum = curr;
// if curr is increase then get
// value in maximum
if(maximum < curr)
maximum = curr;
// traverse right
lengthUtil(root->right, maximum,
minimum, curr + 1);
}
intgetLength(Node* root)
{
intmaximum = 0, minimum = 0;
lengthUtil(root, maximum, minimum, 0);
// 1 is added to include root in the width
return(abs(minimum) + maximum) + 1;
}
// Utility function to create a new tree node
Node* newNode(intdata)
{
Node* curr = newNode;
curr->data = data;
curr->left = curr->right = NULL;
returncurr;
}
// Driver program to test above functions
intmain()
{
Node* root = newNode(7);
root->left = newNode(6);
root->right = newNode(5);
root->left->left = newNode(4);
root->left->right = newNode(3);
root->right->left = newNode(2);
root->right->right = newNode(1);
cout << getLength(root) << "
";
return0;
}
Python3
# Python3 program to prvertical width
# of a tree
# class to create a new tree node
class newNode:
def __init__(self, data):
self.data = data
self.left = self.right = None
# get vertical width
def lengthUtil(root, maximum, minimum, curr = 0):
if (root == None):
return
# traverse left
lengthUtil(root.left, maximum,
minimum, curr – 1)
# if curr is decrease then get
# value in minimum
if (minimum[0] > curr):
minimum[0] = curr
# if curr is increase then get
# value in maximum
if (maximum[0] < curr):
maximum[0] = curr
# traverse right
lengthUtil(root.right, maximum,
minimum, curr + 1)
def getLength(root):
maximum = [0]
minimum = [0]
lengthUtil(root, maximum, minimum, 0)
# 1 is added to include root in the width
return (abs(minimum[0]) + maximum[0]) + 1
# Driver Code
if __name__ == '__main__':
root = newNode(7)
root.left = newNode(6)
root.right = newNode(5)
root.left.left = newNode(4)
root.left.right = newNode(3)
root.right.left = newNode(2)
root.right.right = newNode(1)
print(getLength(root))
# This code is contributed by PranchalK
[tabbyending]
Output:
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.
leave a comment
0 Comments