Search⌘ K
AI Features

Print Tree Perimeter

Explore how to print the perimeter of a binary tree by following a specific order: left boundary, leaf nodes, and right boundary. Learn step-by-step methods using iterative and recursive techniques along with analyzing their time and space complexities. This lesson helps you implement perimeter traversal to handle tree boundary problems effectively.

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 ...

Files
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 << "";
}
...