Boundary Traversal of binary tree
Problem
Given a Binary Tree, find its Boundary Traversal. The traversal should be in the following order:
- 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.
- Leaf nodes: All the leaf nodes except for the ones that are part of left or right boundary.
- 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.
Solution Approach
Expected Time complexity:
Click - to see solution code
- C++
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;
}
};