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.
Note:子树不需要对称,只需要根书的左右是镜像即可。
1 递归,判断leftNode->left和rightNode->right,leftNode->right和rightNode->left,left->val == right->val
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 if(root == NULL) return true; 14 return isSymmetricTree(root->left, root->right); 15 } 16 17 bool isSymmetricTree(TreeNode *left, TreeNode *right) 18 { 19 if(left == NULL && right == NULL) return true; //终止条件 20 if(left == NULL || right == NULL) return false; 21 if(left->val == right->val && //合并 22 isSymmetricTree(left->left, right->right) && 23 isSymmetricTree(right->left, left->right) 24 ) 25 return true; 26 27 return false; 28 } 29 30 };