1.题目:
给你一个二叉树的根节点
root
, 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true
2.代码:
方法一:递归实现
/**
* 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 isSymmetric(TreeNode root) {
boolean result=compare(root.left,root.right);
return result;
}
public boolean compare(TreeNode left,TreeNode right){//确定好递归的参数!
if(left==null && right!=null) return false;//一些特殊情况
if(left!=null && right==null) return false;
if(left==null && right==null) return true;
if(left.val!=right.val) return false;
boolean outside = compare(left.left,right.right);//判断左右子树的外侧是否相同,不断递归
boolean inside = compare(left.right,right.left);//判断左右子树的内侧是否相同,不断递归
return outside&&inside;//当左右子树的内侧和外侧都相同时,才返回true
}
}