Skip to main content

Boundary Traversal of binary tree

Problem

Given a Binary Tree, find its Boundary Traversal. The traversal should be in the following order: 

  1. Left boundary nodes: defined as the path from the root to the left-most node ie- the leaf node you could reach when you always travel preferring the left subtree over the right subtree. 
  2. Leaf nodes: All the leaf nodes except for the ones that are part of left or right boundary.
  3. Reverse right boundary nodes: defined as the path from the right-most node to the root. The right-most node is the leaf node you could reach when you always travel preferring the right subtree over the left subtree. Exclude the root from this as it was already included in the traversal of left boundary nodes.
Note: If the root doesn't have a left subtree or right subtree, then the root itself is the left or right boundary.

Solution Approach

Expected Time complexity: O(n)O(n)

Click - to see solution code
class Solution {
public:
void printleft(Node *root, vector<int> &ans) {
if (root == NULL) {
return;
}
if (root->left != NULL) {
ans.push_back(root->data);
printleft(root->left, ans);
} else if (root->right != NULL) {
ans.push_back(root->data);
printleft(root->right, ans);
}
}

void printleaf(Node *root, vector<int> &ans) {
if (root == NULL) {
return;
}
if (root->left == NULL && root->right == NULL) {
ans.push_back(root->data);
return;
}
printleaf(root->left, ans);
printleaf(root->right, ans);
}

void printright(Node *root, vector<int> &ans) {
if (root == NULL) {
return;
}
if (root->right != NULL) {
printright(root->right, ans);
ans.push_back(root->data);
} else if (root->left != NULL) {
printright(root->left, ans);
ans.push_back(root->data);
}
}

vector<int> boundary(Node *root) {
vector<int> ans;
ans.push_back(root->data);
printleft(root->left, ans);
printleaf(root->left, ans);
printleaf(root->right, ans);
printright(root->right, ans);
return ans;
}
};