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
思路:递归。
struct TreeNode{ int data; TreeNode *left; TreeNode *right; TreeNode(int x):data(x),left(NULL),right(NULL) {} }; bool isMiror(TreeNode *n1,TreeNode *n2) { if(n1 == NULL && n2 == NULL) return true; if(n1 == NULL || n2 == NULL || n1->data != n2->data) return false; return isMiror(n1->left,n2->right) && isMiror(n1->right,n2->left); } bool isSymmetric(TreeNode *root) { if(root==NULL || (root->left == NULL && root->right == NULL)) return true; return isMiror(root->left,root->right); }