解题思路
对称说明左子树的左结点的值等于右子树的右结点的值以及左子树的右结点的值等于左子树的左结点的值。
代码实现
(C#)
/**
* 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) {
return IsMirror(root,root); //小心[]的情况
}
public bool IsMirror(TreeNode t1,TreeNode t2)
{
if(t1==null&&t2==null) return true;
if(t1==null || t2==null || t1.val!=t2.val) return false;
return IsMirror(t1.left,t2.right) && IsMirror(t1.right,t2.left);
}
}
当然也可
public bool IsSymmetric(TreeNode root) {
if (root==null) return true;
return IsMirror(root.left,root.right); //小心[]的情况
}