题目
给定一个二叉树,检查它是否是镜像对称的。
思路
创建IsMirror方法比较两节点是否相同,同时不断递归比较a的左、右孩子节点和b的右、左孩子节点是否相同。
代码块
/**
* 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);
}
public bool IsMirror(TreeNode jroot1 , TreeNode jroot2){
if (jroot1 == null && jroot2 == null)
{
return true;
}
else if (jroot1 == null || jroot2 == null)
{
return false;
}
else if (jroot1.val == jroot2.val)
{
return IsMirror(jroot1.left , jroot2.right) && IsMirror(jroot1.right , jroot2.left);
}
else
{
return false;
}
}
}