给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
一、思路
判定一棵二叉树是否为镜像对称,只需要一个条件:
左子树与右子树是镜像对称的
那么如何判断左子树与右子树是镜像对称的呢?有三个条件:
- 左子树的左子树与右子树的右子树是镜像对称的
- 左子树的右子树与右子树的左子树是镜像对称的
- 左子树的根结点与右子树的根结点相等
C++代码:
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (root == NULL)
return true;
return isMirroringTree(root->left, root->right);
}
bool isMirroringTree(TreeNode* left_tree_root, TreeNode* right_tree_root) {
if (left_tree_root == NULL && right_tree_root == NULL)
return true;
else if (left_tree_root == NULL)
return false;
else if (right_tree_root == NULL)
return false;
else
return (left_tree_root->val == right_tree_root->val) && isMirroringTree(left_tree_root->left, right_tree_root->right) && isMirroringTree(left_tree_root->right, right_tree_root->left);
}
};
执行效率: