标签:
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
Note:
Bonus points if you could solve it both recursively and iteratively.
1 class Solution { 2 public: 3 bool isSym(TreeNode* n1,TreeNode* n2) 4 { 5 if(n1==NULL&&n2!=NULL) return false; 6 if(n1!=NULL&&n2==NULL) return false; 7 if(n1==NULL&&n2==NULL) return true; 8 if(n1->val!=n2->val) return false; 9 10 return isSym(n1->left,n2->right)&&isSym(n1->right,n2->left); 11 } 12 13 bool isSymmetric(TreeNode* root) { 14 if(root==NULL||(!root->left&&!root->right)) return true; 15 return isSym(root->left,root->right); 16 } 17 };
标签:
原文地址:http://www.cnblogs.com/jawiezhu/p/4471624.html