题目描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
这道题要我们写一个函数来看一个二叉树是否对称。
解题思路:
这道题本质上和上一道题没什么区别,所以就不写什么思路了,直接上代码。
代码:
1 /** 2 * Definition for a binary tree node. 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 isSym(TreeNode* q,TreeNode* p){ 13 if(!q&&!p) 14 return true; 15 else if(q&&p) 16 return (q->val==p->val&&isSym(q->left,p->right)&&isSym(q->right,p->left)); 17 else 18 return false; 19 } 20 bool isSymmetric(TreeNode* root) { 21 if(!root) 22 return true; 23 else 24 return isSym(root->left,root->right); 25 } 26 };
他人代码:
1 /** 2 * Definition for a binary tree node. 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 isSym(TreeNode* q,TreeNode* p){ 13 if(!q||!p) 14 //这个条件实际上就是囊括了q和p都为空,和q、p其中一个为空的两种情况。 15 return q==p;//当p、q都空时返回true,另一种情况返回false。实际上和我写的条件本质上没区别,但简洁好多。简直了 16 else if(q&&p) 17 return (q->val==p->val&&isSym(q->left,p->right)&&isSym(q->right,p->left)); 18 } 19 bool isSymmetric(TreeNode* root) { 20 if(!root) 21 return true; 22 else 23 return isSym(root->left,root->right); 24 } 25 };