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 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isSymmetric(TreeNode *root) { 13 // Start typing your C/C++ solution below 14 // DO NOT write int main() function 15 if (!root) return true; 16 17 if(!root->left && !root->right) 18 return true; 19 20 if(!root->left && root->right) 21 return false; 22 23 if(root->left && !root->right) 24 return false; 25 26 if(root->left->val == root->right->val) 27 return symmetricTree(root->left, root->right); 28 else 29 return false; 30 } 31 32 bool symmetricTree(TreeNode *a, TreeNode *b){ 33 if(!a && !b) 34 return true; 35 36 if((!a && b) || (a && !b)) 37 return false; 38 39 if(a->val == b->val) 40 return symmetricTree(a->left, b->right) && symmetricTree(a->right, b->left); 41 else 42 return false; 43 } 44 };
思路:和判断两个tree是否相同有点类似,但是要注意这里判断的是是否对称。好久不写代码,看了别人写的这道题答案,感觉自己写的代码很不标准。不管怎样,先贴出来,慢慢进步吧。