101. Symmetric Tree 發表於 2023-02-13 | 分類於 leetcode problemsolutionoption 1 - dfs12345678910111213class Solution {public: bool sym(TreeNode *l, TreeNode *r){ if(!l && !r) return true; if(!l || !r) return false; if(l->val != r->val) return false; return sym(l->left, r->right) && sym(l->right, r->left); } bool isSymmetric(TreeNode* root) { if(!root) return true; return sym(root->left, root->right); }}; option 2 - bfs1234567891011121314151617181920212223242526272829303132333435class Solution {public: bool isSymmetric(TreeNode* root) { if(!root) return true; int depth = 1; queue<pair<TreeNode*,int>> q ; q.push({root, depth}); while(!q.empty()){ vector<int> rec; int size = q.size(); for(int i=0;i<size; ++i){ auto [p,d] = q.front(); q.pop(); if(p->left) { q.push({p->left, d+1}); rec.push_back(p->left->val); } else rec.push_back(-101); if(p->right){ q.push({p->right, d+1}); rec.push_back(p->right->val); } else rec.push_back(-101); } // check is palindrome int l=0, r = rec.size()-1; while(l<r){ if(rec[l++]!=rec[r--]) return false; } } return true; }};