题目描述
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
But the following is not:
判断一棵二叉树是否对称。
解题思路
根据题目要求,可以认为是树的层序遍历的一种应用。可以递归的判断树的左右子树是否相等。
- 根节点直接递归判断左右子树即可;
- 对于根节点一下的结点,需要判断
- 左结点的左子树和右结点的右子树;
- 左结点的右子树和右结点的左子树
/**
* 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 isSame(TreeNode* left, TreeNode* right)
{
if(!left && !right) return true;
if(left && !right || !left && right) return false;
if(left->val != right->val) return false;
return isSame(left->left, right->right) && isSame(left->right, right->left);
}
bool isSymmetric(TreeNode* root) {
if(!root) return true;
return isSame(root->left, root->right);
}
};