对称二叉树
题目:
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [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
进阶:
你可以运用递归和迭代两种方法解决这个问题吗?
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public bool IsSymmetric(TreeNode root)
{
if(root==null)
{
return true;
}
return isMirror(root.left,root.right);
}
private bool isMirror(TreeNode left,TreeNode right)
{
if(left==null&&right==null)
{
return true;
}
else if(left==null||right==null||left.val!=right.val)
{
return false;
}
else
{
return isMirror(left.left,right.right)&&isMirror(left.right,right.left);
}
}
}