难度Easy
原题连接
内容描述
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
可以直接DFS比较左右两颗子树是否相等,若想等返回true,若不等,返回false
思路 - 时间复杂度: O(N)- 空间复杂度: O(1)******
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool judge(TreeNode* oTree,TreeNode* mTree){
if((oTree != nullptr) && (mTree != nullptr))
{
if((oTree ->val == mTree ->val) && (oTree ->val == mTree ->val))
return judge(oTree ->left,mTree ->right) && judge(oTree ->right,mTree ->left);
return false;
}
if(oTree == mTree)
return true;
return false;
}
bool isSymmetric(TreeNode* root) {
if(root != nullptr)
return judge(root ->left,root ->right);
return true;
}
};