Boundary Traversal of binary tree
struct Node
{
int data;
Node *left, *right;
};
class Solution
{
public:
void call_left(vector<int> &v, Node *root)
{
if (root == NULL)
return;
if (root->left == NULL && root->right == NULL)
return;// don't push the leaf nodes.
v.push_back(root->data);
if (root->left)
call_left(v, root->left);
else
call_left(v, root->right);
}
void call_leaves(vector<int> &v, Node *root)
{
if (root == NULL)
return;
if (root->left == NULL && root->right == NULL)
{
v.push_back(root->data);
}
call_leaves(v, root->left);
call_leaves(v, root->right);
}
void call_right(stack<int> &s, Node *root)
{
if (root == NULL)
return;
if (root->left == NULL && root->right == NULL)
return;// don't push the leaf nodes.
s.push(root->data);
if (root->right != NULL)
call_right(s, root->right);
else
call_right(s, root->left);
}
vector<int> boundary(Node *root)
{
if (root == NULL)
return {};
vector<int> ans;
if (root->left != NULL || root->right != NULL)
ans.push_back(root->data); // for the root node
call_left(ans, root->left); // for left nodes
call_leaves(ans, root); // for leaf nodes.
stack<int> s; // for anticlockwise boundary
// right nodes must be in reverse order, so use stack.
call_right(s, root->right); // for right nodes.
int temp;
while (!s.empty())
{
// extract the right nodes from stack
// topmost right node will be at bottom.
// and the lowermost nodes will be at the
// bottom of the stack.
// Hence, while extracting the nodes,
// the nodes at lower level will come first.
temp = s.top();
s.pop();
ans.push_back(temp);
}
return ans;
}
};
Comments
Post a Comment