MCPcopy Create free account
hub / github.com/codemistic/Data-Structures-and-Algorithms / topview

Function topview

CPP/Trees/TopView_of_tree.cpp:27–68  ·  view source on GitHub ↗

function should print the topView of the binary tree

Source from the content-addressed store, hash-verified

25// function should print the topView of
26// the binary tree
27void topview(Node *root)
28{
29 if (root == NULL)
30 return;
31 queue<Node *> q;
32 map<int, int> m;
33 int hd = 0;
34 root->hd = hd;
35
36 // push node and horizontal distance to queue
37 q.push(root);
38
39 cout << "The top view of the tree is : \n";
40
41 while (q.size())
42 {
43 hd = root->hd;
44
45 // count function returns 1 if the container
46 // contains an element whose key is equivalent
47 // to hd, or returns zero otherwise.
48 if (m.count(hd) == 0)
49 m[hd] = root->data;
50 if (root->left)
51 {
52 root->left->hd = hd - 1;
53 q.push(root->left);
54 }
55 if (root->right)
56 {
57 root->right->hd = hd + 1;
58 q.push(root->right);
59 }
60 q.pop();
61 root = q.front();
62 }
63
64 for (auto i = m.begin(); i != m.end(); i++)
65 {
66 cout << i->second << " ";
67 }
68}
69
70
71int main()

Callers 1

mainFunction · 0.85

Calls 3

pushMethod · 0.45
sizeMethod · 0.45
popMethod · 0.45

Tested by

no test coverage detected