package test; /** * @title:TreeTest * @description: 判断对称二叉树 * @author: dingpeng * @date: 2020/3/10 * @since: Jdk8 */ public class SymmetryTreeTest { public static void main(String[] args) { TreeNode a=new TreeNode(2); a.left=new TreeNode(3); a.right=new TreeNode(3); a.left.left=new TreeNode(4); a.left.right=new TreeNode(5); a.right.left=new TreeNode(null); a.right.right=new TreeNode(4); Solution s =new Solution(); s.isSymmetric(a); } } class Solution { public int isSym = 0; public boolean isSymmetric(TreeNode root) { System.out.println(root); if(root==null){ return true; } TreeNode left = root.left; TreeNode right = root.right; mid(left,right); System.out.println(isSym); return isSym==0?true:false; } //中序遍历 public void mid(TreeNode nodeleft, TreeNode noderight){ if(isSym!=-1){ if(nodeleft!=null&&noderight!=null){ if(nodeleft.val!=noderight.val) { isSym = -1; return; } mid(nodeleft.left, noderight.right); mid(nodeleft.right, noderight.left); }//有空值 else if((nodeleft==null && noderight!=null) ||(nodeleft!=null && noderight==null)){ isSym = -1; return; } } } }