Skip to content

Commit b8b962c

Browse files
+ print binary tree vertical order
> slight changes in other codes
1 parent aa3e40e commit b8b962c

5 files changed

+276
-8
lines changed

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
.idea
1+
.idea
2+
/Scripts/*(Practice).py

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -22,4 +22,6 @@ Following project contains [Python3](https://docs.python.org/3/) implementation
2222
9. Documentation for the GeeksforGeeks page content
2323
```
2424

25-
Note : this is not affiliated with GeeksforGeeks in any way other than for reference.
25+
**Note** : this is not affiliated with GeeksforGeeks in any way other than for reference purpose.
26+
27+
**Also Note** : the code implemetation (and sometimes even algorithm) might be different than the one in GeeksforGeeks. The decision is upon the author and author alone. New Algorithms for the same problem statement may be added in the future.

Scripts/Convert a given Binary Tree to Doubly Linked List.py

+8-4
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,17 @@ def inorder_traverse(head,result):
4343
result=[]
4444
inorder_traverse(head,result)
4545

46-
print("Extracted Double Linked list is :")
47-
print(result)
46+
print("Extracted Double Linked list is")
47+
print(' '.join(str(res) for res in result))
4848

4949
"""
50+
Input Explanation :
51+
Tree is hard-coded as
52+
53+
5054
Output :
51-
Extracted Double Linked list is :
52-
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
55+
Extracted Double Linked list is
56+
0 1 2 3 4 5 6 7 8 9
5357
5458
"""
5559

Scripts/Edit Distance.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -35,9 +35,9 @@ def calculate_distance(s1,s2):
3535
#main
3636
if __name__=="__main__":
3737
s1,s2 = input().split()
38-
dist = calculate_distance(s1,s2)
38+
dist_data = calculate_distance(s1, s2)
3939
print("Number of operations required :")
40-
print(dist)
40+
print(dist_data)
4141

4242
"""
4343
Input Explanation :
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,261 @@
1+
# http://www.geeksforgeeks.org/print-binary-tree-vertical-order/
2+
3+
from collections import defaultdict
4+
5+
6+
# Tree
7+
class Node:
8+
def __init__(self, data):
9+
self.data = data
10+
self.left = None
11+
self.right = None
12+
13+
14+
class ModifiedNode(Node):
15+
def __init__(self, data):
16+
Node.__init__(self, data)
17+
# store Node's Distance from root
18+
self.dist_from_root = None
19+
20+
21+
# Used to store the [Node data] against its {dist_from_root value}
22+
dist_data = defaultdict(list)
23+
24+
25+
def vertical_traverse(head):
26+
# Sort the Dictionary based on its key (distance_from_root)
27+
# print the data
28+
vertical_nodes = []
29+
30+
for key in sorted(dist_data):
31+
data_list = dist_data[key]
32+
# convert list of int to string
33+
data_list = ' '.join(str(x) for x in data_list)
34+
# print(data_list)
35+
vertical_nodes.append(data_list)
36+
37+
return vertical_nodes
38+
39+
40+
def assign_dist(head, distance):
41+
global dist_data
42+
if head is None:
43+
return
44+
45+
# Store the distance in dist_from_data
46+
head.dist_from_root = distance
47+
# Add (append) the dist in a dictionary
48+
dist_data[head.dist_from_root].append(head.data)
49+
50+
# Traverse the child nodes
51+
assign_dist(head.left, distance - 1)
52+
assign_dist(head.right, distance + 1)
53+
54+
55+
# main
56+
if __name__ == "__main__":
57+
"""
58+
Constructing below tree
59+
1
60+
/ \
61+
2 3
62+
/ \ / \
63+
4 5 6 7
64+
\ \
65+
8 9
66+
"""
67+
# Create the above Tree
68+
head = ModifiedNode(1)
69+
70+
head.left = ModifiedNode(2)
71+
head.left.left = ModifiedNode(4)
72+
head.left.right = ModifiedNode(5)
73+
74+
head.right = ModifiedNode(3)
75+
head.right.left = ModifiedNode(6)
76+
head.right.right = ModifiedNode(7)
77+
head.right.left.right = ModifiedNode(8)
78+
head.right.right.right = ModifiedNode(9)
79+
80+
# distance from root to nodes -> dist_from_root
81+
assign_dist(head, 0)
82+
vertical_nodes = vertical_traverse(head)
83+
84+
print("Vertical Traversal")
85+
[print(x) for x in vertical_nodes]
86+
87+
"""
88+
Input Explanation :
89+
Tree is hard-coded as
90+
1
91+
/ \
92+
2 3
93+
/ \ / \
94+
4 5 6 7
95+
\ \
96+
8 9
97+
98+
Output :
99+
Vertical Traversal
100+
4
101+
2
102+
1 5 6
103+
3 8
104+
7
105+
9
106+
107+
"""
108+
109+
'''
110+
Given a binary tree, print it vertically. The following example illustrates vertical order traversal.
111+
112+
1
113+
/ \
114+
2 3
115+
/ \ / \
116+
4 5 6 7
117+
\ \
118+
8 9
119+
120+
121+
The output of print this tree vertically will be:
122+
4
123+
2
124+
1 5 6
125+
3 8
126+
7
127+
9
128+
print-binary-tree-in-vertical-order
129+
130+
Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.
131+
132+
The idea is to traverse the tree once and get the minimum and maximum horizontal distance with respect to root. For the tree shown above, minimum distance is -2 (for node with value 4) and maximum distance is 3 (For node with value 9).
133+
Once we have maximum and minimum distances from root, we iterate for each vertical line at distance minimum to maximum from root, and for each vertical line traverse the tree and print the nodes which lie on that vertical line.
134+
135+
Algorithm:
136+
137+
// min --> Minimum horizontal distance from root
138+
// max --> Maximum horizontal distance from root
139+
// hd --> Horizontal distance of current node from root
140+
findMinMax(tree, min, max, hd)
141+
if tree is NULL then return;
142+
143+
if hd is less than min then
144+
min = hd;
145+
else if hd is greater than max then
146+
*max = hd;
147+
148+
findMinMax(tree->left, min, max, hd-1);
149+
findMinMax(tree->right, min, max, hd+1);
150+
151+
152+
printVerticalLine(tree, line_no, hd)
153+
if tree is NULL then return;
154+
155+
if hd is equal to line_no, then
156+
print(tree->data);
157+
printVerticalLine(tree->left, line_no, hd-1);
158+
printVerticalLine(tree->right, line_no, hd+1);
159+
Implementation:
160+
Following is the implementation of above algorithm.
161+
162+
C++JavaPython
163+
#include <iostream>
164+
using namespace std;
165+
166+
// A node of binary tree
167+
struct Node
168+
{
169+
int data;
170+
struct Node *left, *right;
171+
};
172+
173+
// A utility function to create a new Binary Tree node
174+
Node* newNode(int data)
175+
{
176+
Node *temp = new Node;
177+
temp->data = data;
178+
temp->left = temp->right = NULL;
179+
return temp;
180+
}
181+
182+
// A utility function to find min and max distances with respect
183+
// to root.
184+
void findMinMax(Node *node, int *min, int *max, int hd)
185+
{
186+
// Base case
187+
if (node == NULL) return;
188+
189+
// Update min and max
190+
if (hd < *min) *min = hd;
191+
else if (hd > *max) *max = hd;
192+
193+
// Recur for left and right subtrees
194+
findMinMax(node->left, min, max, hd-1);
195+
findMinMax(node->right, min, max, hd+1);
196+
}
197+
198+
// A utility function to print all nodes on a given line_no.
199+
// hd is horizontal distance of current node with respect to root.
200+
void printVerticalLine(Node *node, int line_no, int hd)
201+
{
202+
// Base case
203+
if (node == NULL) return;
204+
205+
// If this node is on the given line number
206+
if (hd == line_no)
207+
cout << node->data << " ";
208+
209+
// Recur for left and right subtrees
210+
printVerticalLine(node->left, line_no, hd-1);
211+
printVerticalLine(node->right, line_no, hd+1);
212+
}
213+
214+
// The main function that prints a given binary tree in
215+
// vertical order
216+
void verticalOrder(Node *root)
217+
{
218+
// Find min and max distances with resepect to root
219+
int min = 0, max = 0;
220+
findMinMax(root, &min, &max, 0);
221+
222+
// Iterate through all possible vertical lines starting
223+
// from the leftmost line and print nodes line by line
224+
for (int line_no = min; line_no <= max; line_no++)
225+
{
226+
printVerticalLine(root, line_no, 0);
227+
cout << endl;
228+
}
229+
}
230+
231+
// Driver program to test above functions
232+
int main()
233+
{
234+
// Create binary tree shown in above figure
235+
Node *root = newNode(1);
236+
root->left = newNode(2);
237+
root->right = newNode(3);
238+
root->left->left = newNode(4);
239+
root->left->right = newNode(5);
240+
root->right->left = newNode(6);
241+
root->right->right = newNode(7);
242+
root->right->left->right = newNode(8);
243+
root->right->right->right = newNode(9);
244+
245+
cout << "Vertical order traversal is \n";
246+
verticalOrder(root);
247+
248+
return 0;
249+
}
250+
Run on IDE
251+
252+
Output:
253+
Vertical order traversal is
254+
4
255+
2
256+
1 5 6
257+
3 8
258+
7
259+
9
260+
Time Complexity: Time complexity of above algorithm is O(w*n) where w is width of Binary Tree and n is number of nodes in Binary Tree. In worst case, the value of w can be O(n) (consider a complete tree for example) and time complexity can become O(n2).
261+
'''

0 commit comments

Comments
 (0)