题解 | #判断二叉树是否对称#
判断二叉树是否对称
http://www.nowcoder.com/practice/1b0b7f371eae4204bc4a7570c84c2de1
递归
class Solution { public: //递归 bool isSymmetric(TreeNode* root) { // write code here if(!root) return true; return isSymmetric_(root->left, root->right); } bool isSymmetric_(TreeNode* l, TreeNode* r){ if(!l && !r) return true; if(!l || !r) return false; if(l->val != r->val) return false; return isSymmetric_(l->left, r->right) && isSymmetric_(l->right, r->left); } };
非递归
class Solution { public: //非递归 bool isSymmetric(TreeNode* root) { // write code here if (!root || !root->left && !root->right) return true; queue<TreeNode*> q; q.push(root->left); q.push(root->right); while (!q.empty()) { int sz = q.size(); for (int i = 0; i < sz; i += 2) { TreeNode* L = q.front(); q.pop(); TreeNode* R = q.front(); q.pop(); if (!L && !R) continue; else if (!L || !R) return false; else if (L->val != R->val) return false; q.push(L->left); q.push(R->right); q.push(L->right); q.push(R->left); } } return true; } };