1. Level Order Palindrome Verification
Intuition
Traverse tree using BFS level by level. In each level, record values of all nodes (using null for missing nodes). Check if each level array is a palindrome.
When to apply: Basic baseline check.
Algorithm
- Step 1: If root == null return true.
- Step 2: Run BFS storing node values per level including nulls.
- Step 3: If any level is not palindromic, return false.
- Step 4: Return true.
#include <iostream>#include <vector>#include <string>#include <algorithm>using namespace std; class Solution {public: bool isSymmetric(TreeNode* root) { if (!root) return true; queue<TreeNode*> q; q.push(root->left); q.push(root->right); while (!q.empty()) { int sz = q.size(); vector<int> vals; for (int i = 0; i < sz; i += 2) { TreeNode* t1 = q.front(); q.pop(); TreeNode* t2 = q.front(); q.pop(); if (!t1 && !t2) continue; if (!t1 || !t2 || t1->val != t2->val) return false; q.push(t1->left); q.push(t2->right); q.push(t1->right); q.push(t2->left); } } return true; }}; int main() { // Sample driver execution cout << "Execution completed successfully." << endl; return 0;} Time & Space Complexity
- Time complexity:
O(n)— Processes all nodes and checks level arrays. - Space complexity:
O(w)— Queue holds level width.