Print Tree Perimeter

Given a binary tree, print its perimeter nodes.

Statement

Given the root node of a binary tree, print the nodes that form its perimeter (boundary). We must print the perimeter of the binary tree in three phases (order is important):

  1. Left boundary
  2. Leaf nodes
  3. Right boundary

Example

In the following tree, the nodes highlighted in green, form the perimeter.

G root 100 node1 50 root->node1 node2 200 root->node2 node3 25 node1->node3 node4 60 node1->node4 node6 350 node2->node6 node7 10 node3->node7 node8 70 node4->node8 node9 400 node6->node9

The expected output for the tree above is: 100, 50, 25, 10, 70, 400, 350, 200.

Sample input

The input list below represents the level-order traversal of the binary tree:

[100, 50, 200, 25, 60, 350, 10, 70, 400]

Expected output

The sequence below represents the perimeter of the binary tree:

100, 50, 25, 10, 70, 400, 350, 200

Try it yourself

Note: The binary tree node’s class has members left and right to store references to other nodes, along with the member data to hold the node’s value.

main.cpp
BinaryTree.cpp
BinaryTreeNode.cpp
#include "BinaryTree.cpp"
#include <stack>
#include <string>
using namespace std;
void DisplayTreePerimeter(BinaryTreeNode* root) {
// TODO: Write - Your - Code
cout << "";
}
...
Access this course and 1400+ top-rated courses and projects.