Boundary Traversal Recursive Approach


#1

boundarytraversal

Idea is :
1.)Print the nodes present at boundary of left subtree(except leaf node).
2.)Print the leaf nodes.
3.)Print the nodes present at boundary of right subtree(except leaf node).
Follow the order.

 void leftn(TreeNode* A,vector<int>&res){
     if(A == nullptr){
         return;
     }
     if(A->left){
         res.push_back(A->val);
         leftn(A->left,res);
     }
     else if(A->right){
         res.push_back(A->val);
         leftn(A->right,res);
     }
 }
 
 void leafn(TreeNode* A,vector<int>&res){
     if(A == nullptr){
         return;
     }
     if(A->left == nullptr && A->right == nullptr){
         res.push_back(A->val);
     }
     leafn(A->left,res);//call for left subtree
     leafn(A->right,res);//call for right subtree
 }
 
 void rightn(TreeNode* A,vector<int>&res){
     if(A == nullptr){
         return;
     }
     if(A->right){
         rightn(A->right,res);
         res.push_back(A->val);
     }
     else if(A->left){
         rightn(A->left,res);
         res.push_back(A->val);
     }
 }
 void helper(TreeNode* A,vector<int>&res){
     if(A == nullptr){
         return;
     }
     res.push_back(A->val);//push the root node
     leftn(A->left,res);
     leafn(A,res);
     rightn(A->right,res);
 }
 
vector<int> Solution::solve(TreeNode* A) {
    vector<int>res;
    helper(A,res);
    return res;
}