I was asked in an interview to print the border of a binary tree. For example.
1 / \ 2 3 / \ / \ 4 5 6 7 / \ \ 8 9 10
The answer will be: 1, 2, 4, 8, 9, 10, 7, 3
I gave the following answer.
First method:
I used the Bool variable to solve the above problem.
void printLeftEdges(BinaryTree *p, bool print) { if (!p) return; if (print || (!p->left && !p->right)) cout << p->data << " "; printLeftEdges(p->left, print); printLeftEdges(p->right, false); } void printRightEdges(BinaryTree *p, bool print) { if (!p) return; printRightEdges(p->left, false); printRightEdges(p->right, print); if (print || (!p->left && !p->right)) cout << p->data << " "; } void printOuterEdges(BinaryTree *root) { if (!root) return; cout << root->data << " "; printLeftEdges(root->left, true); printRightEdges(root->right, true); }
His answer: you have used the Bool variable so many times. Can you solve it without using it.
Second method:
I just used tree traversal to solve this problem.
1. Print the left boundary in top-down manner. 2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts: 2.1 Print all leaf nodes of left sub-tree from left to right. 2.2 Print all leaf nodes of right subtree from left to right. 3. Print the right boundary in bottom-up manner.
His answer: he, too, was not satisfied with this method. He said that you cross a tree 3 times . That's too much. Give a different solution if you have one.
Third method: This time I went to Order Bypass (BFS) .
1: Print starting and ending node of each level 2: For each other node check if its both the children are <b>NULL</b> then print that node too.
His answer: he was also not happy with this method, because this method takes additional memory of order O (n).
My question is: tell me the method that traverses the tree once, do not use the Bool variable and do not use extra memory. Is it possible?