# Boundary Traversal of binary tree

Given a binary tree, print boundary nodes of the binary tree Anti-Clockwise starting from the root. For example, boundary traversal of the following tree is “20 8 4 10 14 25 22″

We break the problem in 3 parts:
1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
…..2.1 Print all leaf nodes of left sub-tree from left to right.
…..2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.

We need to take care of one thing that nodes are not printed again. e.g. The left most node is also the leaf node of the tree.

Based on the above cases, below is the implementation:

## C++

```/* program for boundary traversal of a binary tree */
#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node *left, *right;
};

// A simple function to print leaf nodes of a binary tree
void printLeaves(struct node* root)
{
if ( root )
{
printLeaves(root->left);

// Print it if it is a leaf node
if ( !(root->left)  &&  !(root->right) )
printf("%d ", root->data);

printLeaves(root->right);
}
}

// A function to print all left boundry nodes, except a leaf node.
// Print the nodes in TOP DOWN manner
void printBoundaryLeft(struct node* root)
{
if (root)
{
if (root->left)
{
// to ensure top down order, print the node
// before calling itself for left subtree
printf("%d ", root->data);
printBoundaryLeft(root->left);
}
else if( root->right )
{
printf("%d ", root->data);
printBoundaryLeft(root->right);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

// A function to print all right boundry nodes, except a leaf node
// Print the nodes in BOTTOM UP manner
void printBoundaryRight(struct node* root)
{
if (root)
{
if ( root->right )
{
// to ensure bottom up order, first call for right
//  subtree, then print this node
printBoundaryRight(root->right);
printf("%d ", root->data);
}
else if ( root->left )
{
printBoundaryRight(root->left);
printf("%d ", root->data);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

// A function to do boundary traversal of a given binary tree
void printBoundary (struct node* root)
{
if (root)
{
printf("%d ",root->data);

// Print the left boundary in top-down manner.
printBoundaryLeft(root->left);

// Print all leaf nodes
printLeaves(root->left);
printLeaves(root->right);

// Print the right boundary in bottom-up manner
printBoundaryRight(root->right);
}
}

// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );

temp->data = data;
temp->left = temp->right = NULL;

return temp;
}

// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root         = newNode(20);
root->left                = newNode(8);
root->left->left          = newNode(4);
root->left->right         = newNode(12);
root->left->right->left   = newNode(10);
root->left->right->right  = newNode(14);
root->right               = newNode(22);
root->right->right        = newNode(25);

printBoundary( root );

return 0;
}
```

## Java

```//Java program to print boundary traversal of binary tree

/* A binary tree node has data, pointer to left child
and a pointer to right child */
class Node
{
int data;
Node left, right;

Node(int item)
{
data = item;
left = right = null;
}
}

class BinaryTree
{
Node root;

// A simple function to print leaf nodes of a binary tree
void printLeaves(Node node)
{
if (node != null)
{
printLeaves(node.left);

// Print it if it is a leaf node
if (node.left == null && node.right == null)
System.out.print(node.data + " ");
printLeaves(node.right);
}
}

// A function to print all left boundry nodes, except a leaf node.
// Print the nodes in TOP DOWN manner
void printBoundaryLeft(Node node)
{
if (node != null)
{
if (node.left != null)
{

// to ensure top down order, print the node
// before calling itself for left subtree
System.out.print(node.data + " ");
printBoundaryLeft(node.left);
}
else if (node.right != null)
{
System.out.print(node.data + " ");
printBoundaryLeft(node.right);
}

// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

// A function to print all right boundry nodes, except a leaf node
// Print the nodes in BOTTOM UP manner
void printBoundaryRight(Node node)
{
if (node != null)
{
if (node.right != null)
{
// to ensure bottom up order, first call for right
//  subtree, then print this node
printBoundaryRight(node.right);
System.out.print(node.data + " ");
}
else if (node.left != null)
{
printBoundaryRight(node.left);
System.out.print(node.data + " ");
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

// A function to do boundary traversal of a given binary tree
void printBoundary(Node node)
{
if (node != null)
{
System.out.print(node.data + " ");

// Print the left boundary in top-down manner.
printBoundaryLeft(node.left);

// Print all leaf nodes
printLeaves(node.left);
printLeaves(node.right);

// Print the right boundary in bottom-up manner
printBoundaryRight(node.right);
}
}

// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(20);
tree.root.left = new Node(8);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(12);
tree.root.left.right.left = new Node(10);
tree.root.left.right.right = new Node(14);
tree.root.right = new Node(22);
tree.root.right.right = new Node(25);
tree.printBoundary(tree.root);

}
}

// This code has been contributed by Mayank Jaiswal(mayank_24)
```

## Python

```
# Python program for binary traversal of binary tree

# A binary tree node
class Node:

# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None

# A simple function to print leaf nodes of a Binary Tree
def printLeaves(root):
if(root):
printLeaves(root.left)

# Print it if it is a leaf node
if root.left is None and root.right is None:
print root.data,

printLeaves(root.right)

# A function to print all left boundary nodes, except a
# leaf node. Print the nodes in TOP DOWN manner
def printBoundaryLeft(root):

if(root):
if (root.left):

# to ensure top down order, print the node
# before calling itself for left subtree
print root.data,
printBoundaryLeft(root.left)

elif(root.right):
print root.data,
printBoundaryRight(root.right)

# do nothing if it is a leaf node, this way we
# avoid duplicates in output

# A function to print all right boundary nodes, except
# a leaf node. Print the nodes in BOTTOM UP manner
def printBoundaryRight(root):

if(root):
if (root.right):
# to ensure bottom up order, first call for
# right subtree, then print this node
printBoundaryRight(root.right)
print root.data,

elif(root.left):
printBoundaryRight(root.left)
print root.data,

# do nothing if it is a leaf node, this way we
# avoid duplicates in output

# A function to do boundary traversal of a given binary tree
def printBoundary(root):
if (root):
print root.data,

# Print the left boundary in top-down manner
printBoundaryLeft(root.left)

# Print all leaf nodes
printLeaves(root.left)
printLeaves(root.right)

# Print the right boundary in bottom-up manner
printBoundaryRight(root.right)

# Driver program to test above function
root = Node(20)
root.left = Node(8)
root.left.left = Node(4)
root.left.right = Node(12)
root.left.right.left =  Node(10)
root.left.right.right = Node(14)
root.right = Node(22)
root.right.right = Node(25)
printBoundary(root)

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

```

Output:
`20 8 4 10 14 25 22`

Time Complexity: O(n) where n is the number of nodes in binary tree.

# Company Wise Coding Practice    Topic Wise Coding Practice

• ANA
• samthebest

in other words the left and right boundary can envelope a leaf node..
so it is not always true that every leaf node will also be a part of boundary

..????????

• ANA

every leaf will be the part of boundary

• samthebest

1
/
2 6
/
3 4 7
/
5 8
/
9

the boundary should 1,2,3,5,6,7,8,9

but 2 . Print all leaf nodes from left to right,
this point will include 4 also ryt..??
can someone clarify the definition boundary or is above algo wrong?

• siddhant

Can anyone tell why was there a need for 2 calls for printing leaf nodes
printLeaves(root->left);
printLeaves(root->right);

cant we just write printLeaves(root);
and it should print all the leaf nodes

A correction is needed for this code please add the return statement in the first if block for this function and same goes for printBoundaryRight otherwise it will print few node values more than once.Please make the correction

void printBoundaryLeft(struct node* root)
{
if (root)
{
if (root->left)
{
// to ensure top down order, print the node
// before calling itself for left subtree
printf(“%d “, root->data);
printBoundaryLeft(root->left);
return;
}
else if( root->right )
{
printf(“%d “, root->data);
printBoundaryLeft(root->right);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

• rlee

This solution works great for printing all the boundary nodes. However, it does not handle the case where a leaf node (e.g., 4) occurs BEFORE another left boundary node. For example, if node 10 has children, we’d have to print node 4 before 10 because 10 would still be a left boundary node.
You can easily see this problem by just looking at how the function calls are made: print left boundary, print leaves, print right boundary.
What if a leaf node occurs before a left boundary node?

• AlienOnEarth

Another algorithm can be:

1.) print left view of the tree
2.) print all the leaves from left to right
3.) print right view of the tree

• danny

I don’t think the above solution will work for skew trees either Left skew or right skew….Please correct me if I am wrong.

• AlienOnEarth

It will work for all type of trees

• danny

Yes,. Got to know . Thanks

• mccullum

20

8
/
4
/
10 14

22

for the tree above shudn’t the ans be 20 10 22 14 8
bt the solution posted gives 20 22 14 4 8

• Rahul

In the boundary traversal as mentioned we have to print .. first left subtree’s boundary , then all leaf nodes and at last right subtree’s boundary in bottom-up manner…
In ur example, 10 is neither in left subtree’s boundary nor in right subtree’s boundary .. hence the required ans. i think should be 20 22 14 4 8

• Sriharsha g.r.v

HI..the same idea but code loooks simple here

printleft(struct node* node)

{

if (node->left == NULL)

return;

printf(“%d “, node->data);

printleft(node->left);

}

printleaves(struct node*root)

{

if(root)

{

printleaves(root->left);

if(root->left==NULL && root->right==NULL)

printf(“%d “,root->data );

printleaves(root->right);

}

}

printright(struct node* node)

{

if (node->right == NULL)

return;
printleft(node->right);

printf(“%d “, node->data);
}

• Rahul

your code will give incorrect output for this …

20

/

8 22

12 25

/

10 14

the correct output should be . 20 8 12 10 14 25 22

but o/p according to ur code is . 20 10 14 25 22

• Gautam

Hey i think your code will not properly work for
20

• @Ankit

i think else if part in printBoundaryLeft and printBoundaryRight function is not necessary

• sh

Another approach could be, use BFS for the tree traversal and enter all the elements in queue where levels are seperated by NULL entries.After completing traversal, start taking out elements from queue, first entry after NULL will be printed, and entry before NULL will be pushed to stack, rest all the entries are ignored. Now, when queue is empty, go on popping elements from the stack until it gets empty.

please mention if it is having problem with some cases.

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• wow code π

• punfabi

for trees in which root doesn’t have left or right child..

``` ```
/* Paste your code here (You may delete these lines if not writing code) */

// A function to do boundary traversal of a given binary tree
void printBoundary (struct node* root)
{
if (root)
{
printf("%d ",root->data);

// Print the left boundary in top-down manner.
if( root->left)
printBoundaryLeft(root->left);
else
printBoundaryLeft(root->right);

// Print all leaf nodes
printLeaves(root->left);
printLeaves(root->right);

// Print the right boundary in bottom-up manner
if( root->right)
printBoundaryRight(root->right);
else
printBoundaryRight(root->left);
}
}
``` ```
• Akshay Jindal

Awesome!!…simplicity at its best..:D

• ushekokar

void boundary(struct node *root1)
{
static struct node *t=root1;
static int leftflag=1;

if(root1->l==NULL&&root1->r==NULL)//dont print leaf nodes
return;

if(leftflag==1&&t->l!=NULL)//check if left of root is not null,if it is null dont go inside
{
cout<<" "<<root1->data;//print data first
if(root1->l!=NULL)
boundary(root1->l);
else if(root1->r!=NULL)
boundary(root1->r);
}

if(root1==t&&leftflag==1)//if left
{
leftflag=0;
printleaf(root1);
}

if(leftflag==0&&t->r!=NULL)//if right is null dont go inside
{
if(root1->r!=NULL)
boundary(root1->r);
else if(root1->l!=NULL)
boundary(root1->l);
if(root1!=t)//dont print root again
cout<<" "<<root1->data;//print data in reverse order
}
}

void printleaf(struct node *t)
{
if(t->l==NULL&&t->r==NULL)
cout<<" "<<t->data;
else
{
if(t->l!=NULL)
printleaf(t->l);
if(t->r!=NULL)
printleaf(t->r);
}
}

• Sunil

There is no need of the ‘else if’ part in both printBoundaryLeft() and printBoundaryRight(). I don’t understand its need. Code works just fine without it.

• Himanshu

@Sunil
There is a need of else if in both functions.
Suppose in the above example node 8 has no left child.
Then the output should be 20 8 12 10 14 25 22.If you remove else if from the functions the output will be
20 10 14 25 22

• Sunil

Thank you so much! It needed explanation!

• denial

I think this code solves problem. works in all case. Correct me if I’m wrong. π

``` ```
#include <stdio.h>
#include <stdlib.h>
// structure declaration of tree node
struct tnode
{
int data;
struct tnode *left;
struct tnode *right;
};
typedef struct tnode node;
node *newNode(int data)
{
node *temp=(node *)malloc(sizeof(node));
temp->data=data;
temp->left=NULL;
temp->right=NULL;
return temp;
}
// function printing left boundary of the tree
void leftBoundary(node *root)
{
if(root)
{
// print the node if it is NOT leaf
if(root->left!=NULL||root->right!=NULL)
printf("%d\t",root->data);
leftBoundary(root->left);
}
}
// function printing right boundary of the tree
void rightBoundary(node *root)
{
if(root)
{
rightBoundary(root->right);
// print the node if it is NOT leaf
if(root->left!=NULL||root->right!=NULL)
printf("%d\t",root->data);
}
}
// function printing all leaves of tree
void printLeaf(node *root)
{
if(root)
{
// traverse in Inorder and print all leaves
printLeaf(root->left);
if(root->left==NULL&&root->right==NULL)
printf("%d\t",root->data);
printLeaf(root->right);
}
}
// function printing boundary of the tree
void printBoundary(node *root)
{
if(root)
{
leftBoundary(root);
printLeaf(root);
rightBoundary(root);
}
}
int main()
{
node *root         		  = newNode(20);
root->left                = newNode(8);
root->left->left          = newNode(4);
root->left->right         = newNode(12);
root->left->right->left   = newNode(10);
root->left->right->right  = newNode(14);
root->right               = newNode(22);
root->right->right        = newNode(25);

printBoundary(root);

return 0;
}
``` ```
• sid

#include

using namespace std;

struct node
{
int data;
struct node *left;
struct node *right;
};

struct node *getnode(int data)
{
struct node *new_node =(struct node *)malloc(sizeof(struct node));
new_node->data=data;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}
void printleftboundary(struct node *node)
{
if(node)
{
if(node->left!=NULL)
{
printf(“%d “,node->data);
printleftboundary(node->left);
}
else if(node->right)
{
printf(“%d “,node->data);
printleftboundary(node->right);
}
}
}

void printrightboundary(struct node *node)
{
if(node)
{
if(node->right!=NULL)
{
printf(“%d “,node->data);
printrightboundary(node->right);
}
else if(node->left)
{
printf(“%d “,node->data);
printrightboundary(node->left);
}
}
}

void printleafnodes(struct node *node)
{
if(!node)
return;

if(!node->left&&!node->right)
printf(“%d “,node->data);

printleafnodes(node->left);
printleafnodes(node->right);
}

void print(struct node *node)
{
struct node *rightnode=node->right,*leftnode=node->left,*tnode=node;

if(!node)
return;
printf(“%d “,node->data);

if((!tnode->left)&&tnode->right)
{
while((!tnode->left)&&tnode->right)
{
tnode=tnode->right;
}

if(tnode->left!=NULL)
{
leftnode=tnode->left;
}
rightnode=node->right;
}

else if(tnode->left&&(!tnode->right))
{
while(tnode->left&&(!tnode->right))
{
tnode=tnode->left;
}

if(tnode->right!=NULL)
{
rightnode=tnode->right;
}
leftnode=node->left;

}

printleftboundary(leftnode);

printleafnodes(node->left);

printleafnodes(node->right);
//printf(“%d”,rightnode->right->data);
printrightboundary(rightnode);
}

int main()
{
struct node *root=getnode(10);
root->left=getnode(5);
root->left->left=getnode(3);
root->left->right=getnode(7);
root->left->left->left=getnode(1);
root->left->right->right=getnode(8);
root->left->left->right=getnode(4);

print(root);
return 0;
}

• koolkeshaw

@GeeksforGeeks

your algo will not work for a node satisfying following condition :-
i) it is neither on left boundary nor on right boundary
ii) only one of its child(either left OR right) is null

refer :
http://ideone.com/QtOivl

I think the correct o/p :- 20,8,23,24,25

• abhinav

just level order traversal and print first and last nodes

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• danny

In the last level you have to print all the values in queue and also the right values will not follow bottom up approach.

• KK

We can do with level order traversal also. Print left node of each level and store the right node in stack. Once we are done with tree traversal print the stack in reverse order.

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• abhishek08aug

Intelligent π

• r…

we can Print all boundary elements in a single iteration O(n)

``` ```
void Boundary_traversal ( bst_node * node ,int lcnt ,int rcnt )
{
if(node == NULL)
return;

if( !rcnt && !isLeaf(node))
{
printf("-> %d ",node->value);
}

Boundary_traversal(node->left ,flag,lcnt+1,rcnt);

if(isLeaf(node))
{
printf("-> %d ",node->value );
}

Boundary_traversal(node->right ,flag,lcnt,rcnt+1);

if(!lcnt && rcnt && !isLeaf(node))
{
printf("-> %d ",node->value );
}

}
``` ```
• r…

fixing the recursive caller function arguments (shouldn’t have flag as the second argument)

``` ```
void Boundary_traversal ( bst_node * node ,int lcnt ,int rcnt )
{
if(node == NULL)
return;

if( !rcnt && !isLeaf(node))
{
printf("-> %d ",node->value);
}

Boundary_traversal(node->left ,lcnt+1,rcnt);

if(isLeaf(node))
{
printf("-> %d ",node->value );
}

Boundary_traversal(node->right,lcnt,rcnt+1);

if(!lcnt && rcnt && !isLeaf(node))
{
printf("-> %d ",node->value );
}

}
``` ```
• Gupt

The above approach seems to be wrong. Consider a tree where the left subtree of root has just one child. But the right subtree has say 10 complete levels. The left boundary of right subtree also becomes the boundary of whole tree. But it wont be printed in this aproach.

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• Anon

this is a valid point.It is a request to please confirm this point!.

• Shrey Trivedi

Then in that case we should do the following :
1. Print the left view of the tree (all nodes that you would see from the left)
2. Print the leaves of the tree
3. Print the right view of the tree bottom to top

• Manish

public void boundaryTraversal(){
boundaryTraversal(root);
}
private void boundaryTraversal(Node root){
leftBoundary(root);
leafNodes(root);
rightBoundary(root.right);

}
private void leftBoundary(Node root){
if(root==null)
return;
while(root.left!=null){
System.out.println(root.key);
root=root.left;
}
}
private void rightBoundary(Node root){
if(root==null)
return;
rightBoundary(root.right);
if(root.right==null){}
else
System.out.println(root.key);

}
private void leafNodes(Node root){
if(root==null)
return;
leafNodes(root.left);
leafNodes(root.right);
if(root.left==null&&root.right==null)
System.out.println(root.key);
}

• amit

I think if we add another node as left of 10 say with value 6, we should get both 10 and 6 in output, but these code wont give 10 in the output

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
#include <stdio.h>
#include <stdlib.h>

/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node *left, *right;
};

// A simple function to print leaf nodes of a binary tree
void printLeaves(struct node* root)
{
if ( root )
{
printLeaves(root->left);

// Print it if it is a leaf node
if ( !(root->left)  &&  !(root->right) )
printf("%d ", root->data);

printLeaves(root->right);
}
}

// A function to print all left boundry nodes, except a leaf node.
// Print the nodes in TOP DOWN manner
void printBoundaryLeft(struct node* root)
{
if (root)
{
if (root->left)
{
// to ensure top down order, print the node
// before calling itself for left subtree
printf("%d ", root->data);
printBoundaryLeft(root->left);
}
else if( root->right )
{
printf("%d ", root->data);
printBoundaryLeft(root->right);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

// A function to print all right boundry nodes, except a leaf node
// Print the nodes in BOTTOM UP manner
void printBoundaryRight(struct node* root)
{
if (root)
{
if ( root->right )
{
// to ensure bottom up order, first call for right
//  subtree, then print this node
printBoundaryRight(root->right);
printf("%d ", root->data);
}
else if ( root->left )
{
printBoundaryRight(root->left);
printf("%d ", root->data);
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

// A function to do boundary traversal of a given binary tree
void printBoundary (struct node* root)
{
if (root)
{
printf("%d ",root->data);

// Print the left boundary in top-down manner.
printBoundaryLeft(root->left);

// Print all leaf nodes
printLeaves(root->left);
printLeaves(root->right);

// Print the right boundary in bottom-up manner
printBoundaryRight(root->right);
}
}

// A utility function to create a node
struct node* newNode( int data )
{
struct node* temp = (struct node *) malloc( sizeof(struct node) );

temp->data = data;
temp->left = temp->right = NULL;

return temp;
}

// Driver program to test above functions
int main()
{
// Let us construct the tree given in the above diagram
struct node *root         = newNode(20);
root->left                = newNode(8);
root->left->left          = newNode(4);
root->left->right         = newNode(12);
root->left->right->left   = newNode(10);
root->left->right->left->left   = newNode(6);
root->left->right->right  = newNode(14);
root->right               = newNode(22);
root->right->right        = newNode(25);

printBoundary( root );

return 0;
}

``` ```
• Gopal

public static void boundaryTraversal(Node root)
{
if(root == null)
return;

boundaryTraversal(root,true,true);
}

private static void boundaryTraversal(Node node,boolean left,boolean right)
{
if(node == null)
return;
//to avoid root to printed twice
boolean isRootPrinted = false;
if(node.left == null && node.right ==null)
{
System.out.print(node.n + " ");
return;
}

if(left)
{
System.out.print(node.n + " ");
isRootPrinted = true;
}

if(left)
boundaryTraversal(node.left,left,false);
else
boundaryTraversal(node.left,false,false);

if(right)
boundaryTraversal(node.right,false,right);
else
boundaryTraversal(node.right,false,false);

if(right && !isRootPrinted)
{
System.out.print(node.n + " ");
}
}

• Karthik

Using Preorder traversal on left tree and postorder traversal on right

void preLeft(Node* node, bool check = true)
{
if(!node)
return;

if(check || !(node->right || node->left))
cout << node->data << endl;

preLeft(node->left,check && true);
preLeft(node->right,false);
}

void postRight(Node* node, bool check = true)
{
if(!node)
return;

postRight(node->left,false);
postRight(node->right,check&&true);

if(check || !(node->right || node->left))
cout << node->data << endl;
}

void boundaryTraversal(Node* root)
{
if(!root)
return;

cout<< root->data<<endl;
preLeft(root->left);
postRight(root->right);
}

class Node
{
public:
Node* left;
Node* right;
int data;
Node(int data, Node*right = NULL, Node* left = NULL):data(data),right(right),left(left){};
};

• I figured out the same and agree with your idea with some changes. It is one pass solution unlike given solution.

For left tree, pre-order traversal, use the information that backtrack has started so stop printing internal nodes.

For right tree, post-order traversal, pass the information to recursive function that which child of current node is part of right boundary.

In both the case, always print leaf node, which can easily be checked.

void preorderPrintBoundary (struct node* root, int& backtrack)
{
if (root)
{
if ((! backtrack) || ((!root->left) && (!root->right)))
printf(“%d “, root->data);

preorderPrintBoundary(root->left, backtrack);
preorderPrintBoundary(root->right, backtrack);
backtrack = 1; // place where backtrack starts, set it forever
}
}

void postorderPrintBoundary (struct node* root, const int& right_boundary)
{
if (root)
{
postorderPrintBoundary(root->left, (right_boundary && root->right == NULL));
postorderPrintBoundary(root->right, right_boundary);
if (right_boundary || ((!root->left) && (!root->right)))
printf(“%d “, root->data);
}
}

void printBoundary (struct node* root)
{
if (root)
{
printf(“%d “, root->data);
int backtrack = 0;
preorderPrintBoundary(root->left, backtrack);
int right_boundary = 1;
postorderPrintBoundary(root->right, right_boundary);
}
}

PrintBoundary requires a correction

if (root and root does not have both child node)
{
print root->data
printBoundary(root’s child which ever is present)
}
else
{ /* root has both the child node, continue with preorder and post order idea */
}

• Amit

Requirement :
1. Print the left boundary in top-down manner.
2. Print all leaf nodes from left to right, which can again be sub-divided into two sub-parts:
β¦..2.1 Print all leaf nodes of left sub-tree from left to right.
β¦..2.2 Print all leaf nodes of right subtree from left to right.
3. Print the right boundary in bottom-up manner.

Solution should be :
1. Root -> Check Not Leaf -> Print -> Recurse to left
2. Inorder Traversal of full tree print only leaves
3. Root -> Recurse to right -> Check Not Leaf -> Print

Am I right looks like simple functions

• Dhaval
``` ```
/*@geeksforgeeks
For the following input...*/
struct node *root         = newNode(20);
root->right                = newNode(8);
root->right->left          = newNode(4);
root->right->right         = newNode(12);
root->right->left->left   = newNode(10);
root->right->right->right  = newNode(14);
root->right->right->left   = newNode(11);
root->right->left->right        = newNode(25);
/*    output:20 10 25 11 14 12 8
20

8

4        12

10    25  11   14

4 is not printed...
I think it should be print 4 as a Left-boundary..
Correct me if I am wrong..

*/
``` ```
• AKS

@Dhaval, Yes, You are right.I too have same question, let me know if you got the answer .

• Sariam

why do well call printLeaves() twice, we can just call it once by passing the root like: printLeaves(root) which will print leaves from left to right which we want.

Clarify if I am missing something!

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• rahul sihag

O(n) in one traversal
Call
printBoundary(root,1,1);

``` ```
int flagl=1;

void printBoundary(struct node *root,int flagr,int rootflag)
{
if(!root)
return;
if(root->left==NULL&&root->right==NULL)
{
printf("%d ",root->data);
flagl=0;
return;
}

if(flagl)
printf("%d ",root->data);

printBoundary(root->left,0,0);
if(flagr)
printBoundary(root->right,1,0);
else
printBoundary(root->right,0,0);
if(flagr&&!rootflag)
printf("%d ",root->data);

}

``` ```
• firefist

fantastic…

• praveen

superb

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• Gupt

Could you please explain the code?

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• Guest

Your code will not work in below example:

• Vaibhav

Your code will not work in below example:
10

20

30

• Nishant Seth

What if nodes 10 & 14 have children as well? I think they should still be part of tree boundary, but they wont be picked by any of the 3 boundary functions. Let me know if I am wrong.

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• Aashish

If 10 and 14 will have children, they will become internal nodes, so they should not be printed.

• Theo

i think 10 and 14 will be still part of the boundary if 10 has only a right child(leaf) and 14 has only a left child(leaf). But your code seems doesn’t handling it..the boundary should contain all left most nodes and right most nodes of n-1 levels and all leaves of nth level for a n level tree….

• Nitin Gutpa iitan

No Need to right else part of PrintLeft and PrintRight boundary function….
pls clarify me …if i m wrong

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• Aashish

Remove node 4 from the example discussed above. The new output should be: 20 8 12 10 14 25 22
This is because, if a subtree has no left child, its right node will serve as the boundary. This will be missed if we remove the else part.

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```
• sahilalipuria
``` ```
/* Paste your code here (You may delete these lines if not writing code) */
the function to print the left and right can be written as

void printleft(node *root)
{
if(root->left==NULL && root->right==NULL)
return;
else
{
printf("%d",root->left->data);
printleft(root->left);
}
}

similarly we can write for the right boundary
``` ```
• atul

printing left and leaf nodes can be done in same function :-
call : print(root);

``` ```
int flag=1;
void printLeftLeaf(node *root)
{
if(root!=NULL)
{
if(flag==1 || (!root->left && !root->right))
{
printf("%d ",root->data);
}
printLeftLeaf(root->left);
flag=0;
printLeftLeaf(root->right);
}

}

void printRight(node *root)
{
if(root!=NULL)
{
if(root->left==NULL && root->right==NULL)
{
return;
}
else
{
printf("%d ",root->data);
printRight(root->right);
}
}

}
node* print(node *root)
{
if(!root)
return NULL;
printLeftLeaf(root);
if(root->right)
{
printRight(root->right);
}
}

``` ```
• atul

printing left and the leaf nodes can be done in single function.
call : print(root);

``` ```
int flag=1;
void printLeftLeaf(node *root)
{
if(root!=NULL)
{
if(flag==1 || (!root->left && !root->right))
{
printf("%d ",root->data);
}
printLeftLeaf(root->left);
flag=0;
printLeftLeaf(root->right);
}

}

void printRight(node *root)
{
if(root!=NULL)
{
if(root->left==NULL && root->right==NULL)
{
return;
}
else
{
printf("%d ",root->data);
printRight(root->right);
}
}

}
node* print(node *root)
{
if(!root)
return NULL;
printLeftLeaf(root);
if(root->right)
{
printRight(root->right);
}
}

``` ```
• sreeram

I think in these printBoundaryLeft and printBoundaryRight
functions …we can go for iterative traversal since it substantially reduces stack calls and memory ….

• ranjan

yes..i agree..
cud u please post ur solution here..

• sreeram
``` ```
void printBoundaryLeft(struct node* root)
{
while (root->left||root->right)
{
if (root->left)
{
// to ensure top down order, print the node
// before calling itself for left subtree
printf("%d ", root->data);
root=root->left;
}
else if( root->right )
{
printf("%d ", root->data);
root=root->right;
}
// do nothing if it is a leaf node, this way we avoid
// duplicates in output
}
}

``` ```
• Siva Krishna

I think here duplicates may come 4 and 25 are printed twice

``` ```
/* Paste your code here (You may delete these lines if not writing code) */
``` ```