We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
//Boundary Traversal of a Binary Tree#include<iostream>#include<vector>usingnamespacestd;structNode{intval;Node*left,*right;Node(intx):val(x),left(nullptr),right(nullptr){}};voidleftBoundary(Node*node,vector<int>&res){if(!node||(!node->left&&!node->right))return;res.push_back(node->val);if(node->left)leftBoundary(node->left,res);elseleftBoundary(node->right,res);}voidleaves(Node*node,vector<int>&res){if(!node)return;if(!node->left&&!node->right)res.push_back(node->val);leaves(node->left,res);leaves(node->right,res);}voidrightBoundary(Node*node,vector<int>&res){if(!node||(!node->left&&!node->right))return;if(node->right)rightBoundary(node->right,res);elserightBoundary(node->left,res);res.push_back(node->val);}vector<int>boundaryTraversal(Node*root){vector<int>res;if(!root)returnres;res.push_back(root->val);leftBoundary(root->left,res);leaves(root->left,res);leaves(root->right,res);rightBoundary(root->right,res);returnres;}intmain(){Node*root=newNode(1);root->left=newNode(2);root->right=newNode(3);root->left->left=newNode(4);root->left->right=newNode(5);root->right->left=newNode(6);root->right->right=newNode(7);vector<int>res=boundaryTraversal(root);for(intx:res)cout<<x<<" ";return0;}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
"Hello World!" in C
You are viewing a single comment's thread. Return to all comments →