思路:
首先我们建立一个判断两棵树是否为镜像的递归函数:
- 判断两个根节点是不是一样。不一样则返回false。
- 判断root1的左子树和root2的右子树是不是镜像对称(递归)。
- 判断root1的右子树和root2的左子树是不是镜像对称(递归) 。
- 如果1,2,3步骤都满足要求,则返回true.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isMirror(TreeNode root1, TreeNode root2)
{
if(root1==null&&root2==null)
return true;
if(!(root1!=null&&root2!=null))
return false;
if(root1.val!=root2.val)
return false;
return isMirror(root1.left,root2.right)&&isMirror(root1.right,root2.left);
}
public boolean isSymmetric(TreeNode root) {
if(root==null)
return false;
return isMirror(root.left,root.right);
}
}