Last active
August 24, 2023 10:52
-
-
Save heysujal/ceb2510c230c7b81939a21f687921003 to your computer and use it in GitHub Desktop.
Iterative Recursive 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: | |
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