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.
思路分析:
对称二叉树需要满足:
根的左孩子和右孩子结点值相等
根的左子树和右子树对称(也就是左子树的左孩子的结点值 == 右子树的右孩子的结点值 && 左子树的右孩子的结点值 == 右子树的左孩子的结点值)
代码:
方法一递归:
/**
* 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) {
if(!root) return true;//****不要忘记判断root是否为空
return isSymNode(root -> left, r -> right);//判断根的左右子树是否对称
}
bool isSymNode(TreeNode* l, TreeNode* r){
if(!l && !r) return true;//左右子树都为空
if(!l || !r) return false;//左右子树有一个为空
if(l -> val == r -> val){//左右子树均不为空,判断左子树和右子树是否均为对称
return isSymNode(l -> left, r -> right) && isSymNode(l -> right, r -> left);
}
return false;
}
};