Print boundary (edge) nodes of a binary tree
Problem: Print all edge nodes of a complete binary tree anti-clockwise.
That is all the left most nodes starting at root, then the leaves left to right and finally all the rightmost nodes.
In other words, print the boundary of the tree.
That is all the left most nodes starting at root, then the leaves left to right and finally all the rightmost nodes.
In other words, print the boundary of the tree.
Algo:
1. Print the leftmost edges from top to bottom.
2. Print the leaves from left to right.
3. Print the rightmost edges. You would need to print from bottom to top. The key is printing in the opposite order. Easy if you know how to manipulate recursion into a stack-based solution.
1. Print the leftmost edges from top to bottom.
2. Print the leaves from left to right.
3. Print the rightmost edges. You would need to print from bottom to top. The key is printing in the opposite order. Easy if you know how to manipulate recursion into a stack-based solution.
Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| void printLeftEdges(BinaryNode p, bool print) { if (p == null ) return ; if (print || (p->left == null && p->right == null )) system.out.print ( " " + p.element); printLeftEdges(p.left, print); printLeftEdges(p.right, (print && p->left == null ? true : false )); } void printRightEdges(BinaryNode p, bool print) { if (p == null ) return ; printRightEdges(p.left, (print && p->right == null ? true : false )); printRightEdges(p.right, print); if (print || (p->left == null && p.right == null )) system.out.print ( " " + p.element); } void printOuterEdges(BinaryNode root{ if (root == null ) return ; system.out.println (root.element); printLeftEdges(root.left, true ); printRightEdges(root.right, true ); }
|
Click here for more Programming Interview Questions
No comments:
Post a Comment