题目要求:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3可以用递归和非递归方式完成,非递归要比递归更容易,效率更高
代码:
class Solution { public: bool isSymmetric(TreeNode *root) { if(root == NULL) return true; return DFS(root->left, root->right); } bool DFS(TreeNode* left, TreeNode* right) { if(left == NULL) return (right == NULL); if(right == NULL) return (left == NULL); if(left->val != right->val) return false; if(!DFS(left->left, right->right)) return false; if(!DFS(left->right, right->left)) return false; return true; } bool NonRecursive(TreeNode* root) { if(root == NULL) return true; queue<TreeNode*> q1; queue<TreeNode*> q2; q1.push(root->left); q2.push(root->right); while(!q1.empty() && !q2.empty()) { TreeNode* node1 = q1.front(); TreeNode* node2 = q2.front(); q1.pop(); q2.pop(); if((node1 == NULL && node2 != NULL) || (node1 != NULL && node2 == NULL)) return false; if(node1 != NULL && node2 != NULL) { if(node1->val != node2->val) return false; q1.push(node1->left); q1.push(node1->right); q2.push(node2->right); q2.push(node2->left); } } return q1.empty() && q2.empty(); } };