题解 | #对称的二叉树#
对称的二叉树
https://www.nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return bool布尔型 */ //思路:对称及子树的左子树等于子树的右子树 public boolean isSame(TreeNode r1,TreeNode r2) { if(r1==null&&r2==null) { return true; } if(r1==null||r2==null) { return false; } if(r1.val!=r2.val) { return false; } //让r1的左与r2的右进行比较,r1的右与r2的左进行比较 return isSame(r1.left,r2.right)&&isSame(r1.right,r2.left); } public boolean isSymmetrical (TreeNode pRoot) { if(pRoot==null) { return true; } return isSame(pRoot.left,pRoot.right); } }