Created
August 24, 2023 10:50
-
-
Save heysujal/8134c442bbce720e99a0e462b2fbf313 to your computer and use it in GitHub Desktop.
Iterative Boundary Level Traversal of Binary tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isLeaf(Node* root){ | |
return !root->left and !root->right; | |
} | |
void addLeftBoundary(Node* root, vector<int> &ans){ | |
Node* curr = root->left; | |
while(curr){ | |
if(!isLeaf(curr)) ans.push_back(curr->data); | |
if(curr->left) curr = curr->left; | |
else curr = curr->right; | |
} | |
} | |
void addLeaves(Node* root, vector<int> &ans){ | |
if(!root) | |
return; | |
if(isLeaf(root)){ | |
ans.push_back(root->data); | |
return; | |
} | |
addLeaves(root->left, ans); | |
addLeaves(root->right, ans); | |
} | |
void addRightBoundary(Node* root, vector<int> &ans){ | |
Node* curr = root->right; | |
vector<int> temp; | |
while(curr){ | |
if(!isLeaf(curr)) temp.push_back(curr->data); | |
if(curr->right) curr = curr->right; | |
else curr = curr->left; | |
} | |
int n = temp.size(); | |
for(int i = n-1; i >= 0; i--){ | |
ans.push_back(temp[i]); | |
} | |
} | |
vector <int> boundary(Node *root) | |
{ | |
vector<int> ans; | |
if(!root) return ans; | |
if(!root->left and !root->right) | |
return {root->data}; | |
ans.push_back(root->data); | |
addLeftBoundary(root,ans); | |
addLeaves(root,ans); | |
addRightBoundary(root,ans); | |
return ans; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment