1. All Boundary Nodes with Set Deduplication
Intuition
Collect all boundary candidate nodes along left path, bottom leaves, and right path into an array and filter out overlaps.
When to apply: Basic baseline check.
Algorithm
- Step 1: Traverse left spine adding all nodes.
- Step 2: Traverse entire tree adding all leaves.
- Step 3: Traverse right spine backwards.
- Step 4: Use a set to eliminate duplicate nodes.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: bool isLeaf(TreeNode* n) { return n && !n->left && !n->right; } void addLeaves(TreeNode* n, vector<int>& res) { if (!n) return; if (isLeaf(n)) { res.push_back(n->val); return; } addLeaves(n->left, res); addLeaves(n->right, res); } vector<int> boundaryTraversal(TreeNode* root) { if (!root) return {}; vector<int> res; if (!isLeaf(root)) res.push_back(root->val); TreeNode* cur = root->left; while (cur) { if (!isLeaf(cur)) res.push_back(cur->val); if (cur->left) cur = cur->left; else cur = cur->right; } addLeaves(root, res); vector<int> rNodes; cur = root->right; while (cur) { if (!isLeaf(cur)) rNodes.push_back(cur->val); if (cur->right) cur = cur->right; else cur = cur->left; } for (int i = (int)rNodes.size() - 1; i >= 0; --i) res.push_back(rNodes[i]); return res; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— All traversals take linear time O(n). - Space complexity:
O(n)— Extra set to deduplicate nodes.