方法1:深度优先遍历
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { //用递归实现 boolean isSymmetrical(TreeNode pRoot) { if(pRoot==null) return true; return isSame(pRoot.left,pRoot.right); } boolean isSame(TreeNode left,TreeNode right){ if(left==null&&right==null){ return true; } if(left!=null&&right!=null&&left.val==right.val){ return isSame(left.left,right.right)&&isSame(left.right,right.left); }else{ return false; } } }
方法2:广度优先遍历
/* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ import java.util.*; public class Solution { boolean isSymmetrical(TreeNode pRoot) { if(pRoot ==null||(pRoot.left==null&&pRoot.right==null)){ return true; } //bfs左子树用 Queue<TreeNode> queueLeft = new LinkedList<>(); //bfs右子树用 Queue<TreeNode> queueRight = new LinkedList<>(); //左子树根节点入队 queueLeft.offer(pRoot.left); //右子树根节点入队 queueRight.offer(pRoot.right); while(true){ //左子树与右子树节点数不等,直接false if(queueLeft.size()!=queueRight.size()){ return false; } //左右子树遍历完毕 返回true if(queueLeft.size()==0&&queueRight.size()==0){ return true; } //左子树当前层节点数 int L = queueLeft.size(); //右子树当前层节点数 int R = queueRight.size(); for(int i=0;i<L;i++){ TreeNode left = queueLeft.poll(); TreeNode right = queueRight.poll(); if(left.val!=right.val){ //对比对称节点的节点值,不等直接false return false; }; if(left.left!=null&&right.right!=null){ //左子树从左向右入队 queueLeft.offer(left.left); //右子树从右向左入队 queueRight.offer(right.right); }else if(left.left!=right.right){ //一个为null一个不为null 直接返回false return false; } //思路同上 if(left.right!=null&&right.left!=null){ queueLeft.offer(left.right); queueRight.offer(right.left); }else if(left.right!=right.left){ return false; } } } } }