给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树
[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
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
第一种使用递归意思也很简单,就是不断依次从外向内比较俩个节点是否相同:
/// <summary>
/// 递归
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public static bool Method1(TreeNode root)
{
if (root == null) return true;
return CompareRoot(root.left, root.right);
}
private static bool CompareRoot(TreeNode lRoot, TreeNode RRoot)
{
if (lRoot == null) return RRoot == null;
if (RRoot == null) return false;
if (lRoot.val != RRoot.val) return false;
return (lRoot.val == lRoot.val) && CompareRoot(lRoot.left, RRoot.right) && CompareRoot(lRoot.right, RRoot.left);
}
迭代的话我是用循环的中序遍历,然后打印出的中序遍历结果再做判断,也就是对称的就是回文这点进行判断:
/// <summary>
/// 非递归实现
/// </summary>
/// <returns></returns>
public static bool Method2(TreeNode root)
{
List<int> listNums = new List<int>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode pNode = root;
//循环中序遍历
while (pNode != null || stack.Count > 0)
{
if (pNode != null)
{
stack.Push(pNode);
pNode = pNode.left;
}
else
{
TreeNode node = stack.Pop();
listNums.Add(node.val);
pNode = node.right;
}
}
//判断是否是回文,是就是对称二叉树
for (int i = 0; i < listNums.Count >> 1; i++)
{
if (listNums[i] != listNums[listNums.Count - 1 - i]) return false;
}
return true;
}