recursively
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
|
class Solution { public: bool isSymmetric(TreeNode* root) { return isTwoTreesSymmetric(root->left, root->right); } private: bool isTwoTreesSymmetric(TreeNode* lTree, TreeNode* rTree) { if((!lTree && rTree) || (!rTree && lTree)) return false; if(!lTree && !rTree) return true; if(lTree->val == rTree->val) return isTwoTreesSymmetric(lTree->left, rTree->right) && isTwoTreesSymmetric(lTree->right, rTree->left); return false; } };
|
iteratively queue
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class Solution { public: bool isSymmetric(TreeNode* root) { queue<TreeNode*> q; q.push(root); q.push(root); while(!q.empty()) { auto t1 = q.front(); q.pop(); auto t2 = q.front(); q.pop(); if(!t1 && !t2) continue; if(!t1 || !t2) return false; if(t1->val != t2->val) return false; q.push(t1->left); q.push(t2->right); q.push(t1->right); q.push(t2->left); } return true; } };
|
iteratively stack
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
|
class Solution { public: bool isSymmetric(TreeNode* root) { stack<TreeNode*> s; s.push(root); s.push(root); while(!s.empty()) { auto t1 = s.top(); s.pop(); auto t2 = s.top(); s.pop(); if(!t1 && !t2) continue; if(!t1 || !t2) return false; if(t1->val != t2->val) return false; s.push(t1->left); s.push(t2->right); s.push(t1->right); s.push(t2->left); } return true; } };
|
上述方法从root开始比较了两次,不好,下面改改 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
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()) { auto p1 = q.front(); q.pop(); auto p2 = q.front(); q.pop(); if(!p1 && !p2) continue; if(!p1 || !p2) return false; if(p1->val != p2->val) return false; q.push(p1->left); q.push(p2->right); q.push(p1->right); q.push(p2->left); } return true; } };
|