1
+ /*
2
+ The Problem is to print Boundary elements of a binary tree
3
+ For Example, Lets say our tree is
4
+ 0
5
+ / \
6
+ 5 6
7
+ / \ / \
8
+ 9 65 7 10
9
+ / \ / \
10
+ 8 12 1 98
11
+
12
+ Then its output should be
13
+ 0->5->9->8->12->1->98->7->10->6
14
+
15
+ My approach for this problem is to split this problem into three simpler problems
16
+ 1. Printing the Left Part of boundary ( excluding the leaf in left part)
17
+ 2. Printing the leaves of tree
18
+ 3. Printing the right part in bottom up manner ( excluding the leaf in right part)
19
+
20
+ */
21
+ #include < iostream>
22
+ #include < stack>
23
+ using namespace std ;
24
+ template <typename T>
25
+ struct TreeNode
26
+ {
27
+ T val;
28
+ TreeNode *left;
29
+ TreeNode *right;
30
+ TreeNode (T vl) // This Constructor helps in Creating a new Tree node with value vl
31
+ {
32
+ val = vl;
33
+ left = NULL ;
34
+ right = NULL ;
35
+ }
36
+ TreeNode (T vl, TreeNode *lft, TreeNode *rt)
37
+ {
38
+ val = vl;
39
+ left = lft;
40
+ right = rt;
41
+ }
42
+ void addChilds (T lVal, T rVal)
43
+ {
44
+ TreeNode *lft = new TreeNode (lVal);
45
+ TreeNode *rt = new TreeNode (rVal);
46
+ left = lft;
47
+ right = rt;
48
+ }
49
+ };
50
+
51
+ template <typename T>
52
+ void printLeftPart (TreeNode<T> *root)
53
+ {
54
+ if (root == NULL )
55
+ return ;
56
+ if (root->left == NULL && root->right == NULL )
57
+ return ;
58
+ cout << root->val << " " ;
59
+ printLeftPart (root->left );
60
+ }
61
+ template <typename T>
62
+ void printRightPart (TreeNode<T> *root)
63
+ {
64
+ if (root == NULL )
65
+ return ;
66
+ if (root->left == NULL && root->right == NULL )
67
+ return ;
68
+ printRightPart (root->right );
69
+ cout << root->val << " " ;
70
+ }
71
+ template <typename T>
72
+ void printLeaves (TreeNode<T> *root)
73
+ {
74
+ if (root == NULL )
75
+ return ;
76
+ if (root->left == NULL && root->right == NULL )
77
+ {
78
+ cout << root->val << " " ;
79
+ return ;
80
+ }
81
+ printLeaves (root->left );
82
+ printLeaves (root->right );
83
+ }
84
+ template <typename T>
85
+ void printBoundary (TreeNode<T> *root)
86
+ {
87
+ cout << " Boundary Elements are : " ;
88
+ printLeftPart (root);
89
+ printLeaves (root);
90
+ printRightPart (root->right );
91
+ cout << " \n " ;
92
+ }
93
+ int main ()
94
+ {
95
+ TreeNode<int > root (0 );
96
+ root.addChilds (5 , 6 );
97
+ root.left ->addChilds (9 , 65 );
98
+ root.left ->left ->addChilds (8 , 12 );
99
+ root.left ->right ->addChilds (1 , 98 );
100
+ root.right ->addChilds (7 , 10 );
101
+ printBoundary (&root);
102
+ // cout << root.val << " " << root.left->val << " " << root.right->val;
103
+ // printInorder(&root);
104
+ return 0 ;
105
+ }
0 commit comments