Skip to content

Instantly share code, notes, and snippets.

@heysujal
Last active August 24, 2023 10:52
Show Gist options
  • Save heysujal/ceb2510c230c7b81939a21f687921003 to your computer and use it in GitHub Desktop.
Save heysujal/ceb2510c230c7b81939a21f687921003 to your computer and use it in GitHub Desktop.
Iterative Recursive Boundary Level Traversal of Binary Tree
class Solution {
public:
void traverseLeft(Node* root, vector<int> &ans){
if(!root or (!root->left and !root->right)) 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){
if(!root) return;
if(!root->left and !root->right){
ans.push_back(root->data);
return;
}
traverseLeaf(root->left, ans);
traverseLeaf(root->right, ans);
}
void traverseRight(Node* root, vector<int> &ans){
if(!root or (!root->left and !root->right)) return;
if(root->right) traverseRight(root->right, ans);
else traverseRight(root->left, ans);
ans.push_back(root->data);
}
vector <int> boundary(Node *root)
{
if(!root) return {};
vector<int> ans;
ans.push_back(root->data);
traverseLeft(root->left, ans);
traverseLeaf(root->left, ans);
traverseLeaf(root->right, ans);
traverseRight(root->right, ans);
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment