文章目录
- 题目描述
- 代码 & 思路
题目描述
- 回溯,由最小子树的镜像,得到次小子树的镜像判断,一直回溯到根结点即可
代码 & 思路
/*** 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) {// 从root开始,进行左右子树的镜像判断return isMirror(root,root);}boolean isMirror(TreeNode left, TreeNode right){// 同时为空,镜像回trueif(left == null && right == null){return true;}// 单个为空,非镜像回falseif(left == null || right == null){return false;}// 分别对当前值、当前两值的左右子树进行判断。return (left.val == right.val) && (isMirror(right.right,left.left)) && (isMirror(right.left,left.right));}
}