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
题目大意要求我们 判断给出的二叉树是否最对称。
最开始想到的是 用数组存储 左子树-根节点-右子树的顺序遍历和按照右子树-根节点-左子树的顺序遍历 的结果 可以过大部分点 但是因为 当某个节点是NULL的时候 是不存进的数组的 比如一边带NULL的 我们可以用递归来解决。
/**
* 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 isSymmetric(TreeNode* root) {
return dfs(root,root);
}
bool dfs(TreeNode* q,TreeNode*p)
{
if(q==NULL&&p==NULL)
return true;
if(q==NULL||p==NULL)
return false;
return (q->val==p->val)&&dfs(q->left,p->right)&&dfs(q->right,p->left);
}
};