Boundary Traversal of binary tree | Practice | GeeksforGeeks

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.

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.
Note: If the root doesn't have a left subtree or right subtree, then the root itself is the left or right boundary. 

Example 1:
Input:
        1 
      /   \
     2     3  
    / \   / \ 
   4   5 6   7
      / \
     8   9
   
Output: 1 2 4 8 9 6 7 3
Explanation:



 
Example 2:
Input:
            1
           / 
          2
        /  \
       4    9
     /  \    \
    6    5    3
             /  \
            7     8

Output: 1 2 4 6 5 7 8
Explanation: 
As you can see we have not taken right
subtree. See Note


 
Your Task:
This is a function problem. You don't have to take input. Just complete the function boundary() that takes the root node as input and returns an array containing the boundary values in anti-clockwise.
 
Expected Time Complexity: O(N). 
Expected Auxiliary Space: O(Height of the Tree).
 
Constraints:
1 ≤ Number of nodes ≤ 105
1 ≤ Data of a node ≤ 105
+1
parasdhanwal268 hours ago
class Solution
{
ArrayList <Integer> boundary(Node root)
{
    ArrayList<Integer> a = new ArrayList<>();
    if(root==null)
    {
        return a;
    }
    if(isLeaf(root)==false)
    {
        a.add(root.data);
        
    }
   
    leftside(root,a);
    leaf(root,a);
    rightside(root,a);
    return a;
   
}
   static boolean isLeaf(Node root)
   {
       if(root.left==null && root.right==null)
       {
           return true;
       }
       else
       {
           return false;
       }
   }
   public static void leftside(Node root,ArrayList<Integer> a)
   {
       Node temp=root.left;
       while(temp!=null)
       {
           if(isLeaf(temp)==false)
           {
               a.add(temp.data);
           }
           
           if(temp.left!=null)
           {
               temp=temp.left;
           }
           else
           {
               temp=temp.right;
           }
       }
   }
   public static void rightside(Node root,ArrayList<Integer> a)
   {
       Node temp=root.right;
       Stack<Integer> s = new Stack<>();
       while(temp!=null)
       {
           if(isLeaf(temp)==false)
           {
               s.push(temp.data);
           }
           
           if(temp.right!=null)
           {
               temp=temp.right;
           }
           else
           {
               temp=temp.left;
           }
       }
       while(!s.isEmpty())
       {
           a.add(s.pop());
       }
   }
   public static void leaf(Node root,ArrayList<Integer> a)
   {
       if(isLeaf(root))
       {
           a.add(root.data);
           return;
       }
       
      if(root.left!=null)
      {
          leaf(root.left,a);
      }
       if(root.right!=null)
       {
           leaf(root.right,a);
       }
   }
   
}
0
soumyajitpatnaik20012 days ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;#define MAX_HEIGHT 100000
// Tree Nodestruct Node{   int data;   Node* left;   Node* right;};
// Utility function to create a new Tree NodeNode* newNode(int val){   Node* temp = new Node;   temp->data = val;   temp->left = NULL;   temp->right = NULL;
   return temp;}
// Function to Build TreeNode* buildTree(string str){   // Corner Case   if(str.length() == 0 || str[0] == 'N')       return NULL;
   // Creating vector of strings from input   // string after spliting by space   vector<string> ip;
   istringstream iss(str);   for(string str; iss >> str; )       ip.push_back(str);
   // Create the root of the tree   Node* root = newNode(stoi(ip[0]));
   // Push the root to the queue   queue<Node*> queue;   queue.push(root);
   // Starting from the second element   int i = 1;   while(!queue.empty() && i < ip.size()) {
       // Get and remove the front of the queue       Node* currNode = queue.front();       queue.pop();
       // Get the current node's value from the string       string currVal = ip[i];
       // If the left child is not null       if(currVal != "N") {
           // Create the left child for the current node           currNode->left = newNode(stoi(currVal));
           // Push it to the queue           queue.push(currNode->left);       }
       // For the right child       i++;       if(i >= ip.size())           break;       currVal = ip[i];
       // If the right child is not null       if(currVal != "N") {
           // Create the right child for the current node           currNode->right = newNode(stoi(currVal));
           // Push it to the queue           queue.push(currNode->right);       }       i++;   }
   return root;}
 
 
 
 
// } Driver Code Ends/* A binary tree Nodestruct Node{   int data;   Node* left, * right;}; */
class Solution {public:   void traverseLeft(Node* root, vector<int> &ans)   {       if(root == NULL){           return;       }       if(root->left == NULL && root->right == NULL) {           return;       }       ans.push_back(root->data);       if(root->left) {           traverseLeft(root->left, ans);       }       else {           traverseLeft(root->right, ans);       }   }      void traverseLeaf(Node* root, vector<int> &ans) {       //base case       if(root == NULL) {           return;       }       if(root->left == NULL && root->right == NULL) {           ans.push_back(root->data);           return;       }              traverseLeaf(root->left, ans);       traverseLeaf(root->right, ans);   }      void traverseRight(Node* root, vector<int> &ans) {       //base case       if(root == NULL) {           return;   //kya hi kar lenge agar root hi null hai....return hi karna hai..band raasta       }       if(root->left == NULL && root->right == NULL) {           return;       }              if(root->right){           traverseRight(root->right, ans);       }       else           traverseRight(root->left, ans);                     //wapas aate waqt       ans.push_back(root->data);                 }      vector <int> boundary(Node *root)   {       //Your code here       vector<int> ans;       if(root == NULL) {           return ans;       }              ans.push_back(root->data);              traverseLeft(root->left, ans);       traverseLeaf(root->left, ans);       traverseLeaf(root->right, ans);       traverseRight(root->right, ans);                   return ans;   }};
// { Driver Code Starts.
/* Driver program to test size function*/
int main() {   int t;   string tc;   getline(cin, tc);   t=stoi(tc);   while(t--)   {       string s ,ch;       getline(cin, s);       Node* root = buildTree(s);       Solution ob;       vector <int> res = ob.boundary(root);       for (int i : res) cout << i << " ";       cout << endl;   }   return 0;}  // } Driver Code Ends
+1
priyalkhapekar14426 days ago
void traverseLeft(Node* root,vector<int> &ans){
        if((root==NULL) || (root->left==NULL && root->right==NULL)){
            return;
        }
        ans.push_back(root->data);
        if(root->left)
          traverseLeft(root->left , ans);
        else if(root->right)
          traverseLeft(root->right , ans);
    }
    void traverseLeaf(Node* root,vector<int> &ans){
        if(root==NULL){
            return;
        }
        if(root->left==NULL && root->right==NULL){
            ans.push_back(root->data);
            return;
        }
        traverseLeaf(root->left,ans);
        traverseLeaf(root->right,ans);
    }
    void traverseRight(Node* root,vector<int> &ans){
        if((root==NULL) || (root->left==NULL && root->right==NULL)){
            return;
        }
        if(root->right)
           traverseRight(root->right,ans);
        else
           traverseRight(root->left,ans);
        ans.push_back(root->data);
    }
    vector <int> boundary(Node *root)
    {
        vector<int> ans;
        if(root==NULL){
            return ans;
        }
        //For ROOT Node
        ans.push_back(root->data);
        //Left Part
        traverseLeft(root->left , ans);
        //For Left LEAF Node
        traverseLeaf(root->left , ans);
        //For Right Leaf Node
        traverseLeaf(root->right , ans);
        //Right Part
        traverseRight(root->right , ans);
        return ans;
    }
+1
wolfofsv6 days ago
void TravLeftBnd(Node* root, vector<int>& boundary){
        if(root){
            if(root -> left){
                boundary.push_back(root -> data);
                TravLeftBnd(root -> left, boundary);
            }
            else if(root -> right){
                boundary.push_back(root -> data);
                TravLeftBnd(root -> right, boundary);
            }
        }
    }
    
    void TravRightBnd(Node* root, vector<int>& boundary){
        if(root){
            if(root -> right){
                TravRightBnd(root -> right, boundary);
                boundary.push_back(root -> data);
            }
            else if(root -> left){
                TravRightBnd(root -> left, boundary);
                boundary.push_back(root -> data);
            }
        }
    }
    
    void TravLeaves(Node* root, vector<int>& boundary){
        if(root){
            if(root -> left == NULL && root -> right == NULL){
                boundary.push_back(root -> data);
            }
            TravLeaves(root -> left, boundary);
            TravLeaves(root -> right, boundary);
        }
    }

    vector <int> boundary(Node *root)
    {
        //Your code here
        vector<int>boundary;
        boundary.push_back(root -> data);
        TravLeftBnd(root -> left, boundary);
        if(root -> left || root -> right)
            TravLeaves(root, boundary);
        TravRightBnd(root -> right, boundary);
        
        return boundary;
    }
0
aishapervin032 weeks ago
void solveleft(Node* node,vector<int> &left)
{
    
    if(node==NULL || (node->left==NULL && node->right==NULL))
    return;
    left.push_back(node->data);
    if(node->left)
    solveleft(node->left,left);
    else
    solveleft(node->right,left);
    
}


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

void solveright(Node* node,vector<int> &right)
{
    
    if(node==NULL || (node->left==NULL && node->right==NULL))
    return;
    right.push_back(node->data);
    if(node->right)
    solveright(node->right,right);
    else
    solveright(node->left,right);
    
}


    vector <int> boundary(Node *root)
    {
        if(root==NULL)
        return {};
        if(root->left==NULL && root->right==NULL)
        return {root->data};
        vector<int>ans;
        ans.push_back(root->data);
        vector<int>leaf;
        vector<int>left;
        vector<int>right;
        solveleft(root->left,left);
        solveleaf(root,leaf);
        solveright(root->right,right);
        reverse(right.begin(),right.end());
        for(int i=0;i<left.size();i++)
          ans.push_back(left[i]);
        for(int i=0;i<leaf.size();i++)
          ans.push_back(leaf[i]);
        for(int i=0;i<right.size();i++)
          ans.push_back(right[i]);
        return ans;
    }
0
koulikmaity3 weeks ago
void traversalLeft(Node* root, vector<int>& ans)   {       // base case      if(root == NULL)          return;      if(root->left == NULL && root->right == NULL)          return;            ans.push_back(root->data);      if(root->left)          traversalLeft(root->left, ans);      else          traversalLeft(root->right, ans);         }      void traversalLeave(Node* root, vector<int>& ans)   {       // base case       if(root == NULL)           return;       if(root->left == NULL && root->right == NULL)       {           ans.push_back(root->data);           return;       }       traversalLeave(root->left, ans);       traversalLeave(root->right, ans);   }      void traverselRight(Node* root, vector<int>& ans)   {       // base case       if(root == NULL)           return;       if(root->left == NULL && root->right == NULL)           return;                  if(root->right)           traverselRight(root->right, ans);        else           traverselRight(root->left, ans);                             ans.push_back(root->data);   }      vector <int> boundary(Node *root)   {       vector<int>ans;       if(root == NULL)       {           return ans;       }       ans.push_back(root->data);              // left part print/store       traversalLeft(root->left, ans);              // leave part print/store       traversalLeave(root->left, ans);       traversalLeave(root->right, ans);              // right part print/store       traverselRight(root->right, ans);              return ans;          }
+2
amanasati13 weeks ago
class Solution:
    def leftsolve(self,root):
        if root:
            if root.left:
                self.stack.append(root.data)
                self.leftsolve(root.left)
            elif root.right:
                self.stack.append(root.data)
                self.leftsolve(root.right)
        
    def rightsolve(self,root):
        if root:
            if root.right:
                self.rightsolve(root.right)
                self.stack.append(root.data)
            elif root.left:
                self.rightsolve(root.left)
                self.stack.append(root.data)
            
    def leavessolve(self,root):
        if root:
            self.leavessolve(root.left)
            
            if (root.left is None) and (root.right is None):
                self.stack.append(root.data)
                
            self.leavessolve(root.right)
            
            
    def printBoundaryView(self, root):
        # Code here
        self.stack=[]
        if root:
            self.stack.append(root.data)
            self.leftsolve(root.left)
            self.leavessolve(root.left)
            self.leavessolve(root.right)
            self.rightsolve(root.right)
        return self.stack
0
amishasahu3281 month ago
class Solution {
    bool isLeaf(Node *node)
    {
        return (!(node->left) && (!node->right));
    }
    void leftBoundary(Node *node, vector<int> &res)
    {
        Node *curr = node->left;
        while(curr)
        {
            if(!isLeaf(curr))  res.push_back(curr->data);
            if(curr->left) curr = curr->left;
            else curr = curr->right;
        }
    }
    void addLeaves(Node *node, vector<int> &res)
    {
        if(isLeaf(node))
        {
              res.push_back(node->data);
              return;
        }
        if(node->left) addLeaves(node->left, res);
        if(node->right) addLeaves(node->right, res);
    }
    void rightBoundary(Node *node, vector<int> &res)
    {
        Node *curr = node->right;
        stack<int> s;
        while(curr)
        {
            if(!isLeaf(curr))  s.push(curr->data);
            if(curr->right) curr = curr->right;
            else curr = curr->left;
        }
        while(!s.empty())
        {
            res.push_back(s.top());
            s.pop();
        }
    }
public:
    vector <int> boundary(Node *root)
    {
        //Your code here
        vector<int> res;
        if(!root) return res;
        if(!isLeaf(root)) res.push_back(root->data);
        leftBoundary(root, res);
        addLeaves(root, res);
        rightBoundary(root, res);
    }
};
+1
jaydhurat1 month ago
class Solution
{
ArrayList <Integer> boundary(Node root)
{
    ArrayList<Integer> a = new ArrayList<>();
    if(root==null)
    {
        return a;
    }
    if(isLeaf(root))
    {
        a.add(root.data);
        return a;
    }
    else
    {
        a.add(root.data);
    }
    leftside(root,a);
    leaf(root,a);
    rightside(root,a);
    return a;
   
}
   static boolean isLeaf(Node root)
   {
       if(root.left==null && root.right==null)
       {
           return true;
       }
       else
       {
           return false;
       }
   }
   public static void leftside(Node root,ArrayList<Integer> a)
   {
       Node temp=root.left;
       while(temp!=null)
       {
           if(isLeaf(temp)==false)
           {
               a.add(temp.data);
           }
           
           if(temp.left!=null)
           {
               temp=temp.left;
           }
           else
           {
               temp=temp.right;
           }
       }
   }
   public static void rightside(Node root,ArrayList<Integer> a)
   {
       Node temp=root.right;
       Stack<Integer> s = new Stack<>();
       while(temp!=null)
       {
           if(isLeaf(temp)==false)
           {
               s.push(temp.data);
           }
           
           if(temp.right!=null)
           {
               temp=temp.right;
           }
           else
           {
               temp=temp.left;
           }
       }
       while(!s.isEmpty())
       {
           a.add(s.pop());
       }
   }
   public static void leaf(Node root,ArrayList<Integer> a)
   {
       if(isLeaf(root))
       {
           a.add(root.data);
           return;
       }
       
      if(root.left!=null)
      {
          leaf(root.left,a);
      }
       if(root.right!=null)
       {
           leaf(root.right,a);
       }
   }
   
}

0
kgeekcs2191 month ago
class Solution {      bool isleaf(Node* root){       if(!root->left && !root->right) return true;       return false;   }   void left_boundary(Node* root,vector<int> &v){   if(root==nullptr) return;      if(!isleaf(root))    v.push_back(root->data);      if(root->left)  left_boundary(root->left,v);   else if(root->right) left_boundary(root->right,v);   }
 
void leaf_node(Node* root,vector<int> &v)  //inorder Traversal{      if(root==nullptr) return;      if(root->left) leaf_node(root->left,v);   if(isleaf(root))    {       v.push_back(root->data);   }   if(root->right) leaf_node(root->right,v);   }
 
void right_boundary(Node* root,vector<int> &v){   if(root==nullptr) return;      if(root->right)  right_boundary(root->right,v);   else if(root->left) right_boundary(root->left,v);      if(!isleaf(root))    v.push_back(root->data);         }
public:   vector <int> boundary(Node *root)   {       //Your code here       vector<int> v;    if(root==nullptr) return v;        v.push_back(root->data);        if(isleaf(root))    {        return v;            }    left_boundary( root->left,v);    leaf_node( root,v);    right_boundary(root->right,v);    return v;   }}; 
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.