1- 思路
借助队列
1- 创建队列 :Queue<TreeNode> queue
,初始化加入 root.left
和 root.right
2- 判断逻辑 :while(!queue.isEmpty()) 2-1 弹出两个结点: 分别为 l
和 r
① 情况1:l == null
且 r ==null
此时,直接 continue
② 情况2:l == null
且 r !=null
此时,直接 返回 false
③ 情况3:l != null
且 r ==null
此时,直接 返回 false
④ 情况4:l.val != r.val
直接返回 false
2-2 入栈顺序 先入栈 l.left
,再入栈 r.right
先入栈 l.right
,再入栈 r.left
2- 实现
⭐101. 对称二叉树——题解思路
class Solution { public boolean isSymmetric ( TreeNode root) { Queue < TreeNode > queue = new LinkedList < > ( ) ; queue. offer ( root. left) ; queue. offer ( root. right) ; while ( ! queue. isEmpty ( ) ) { TreeNode l = queue. poll ( ) ; TreeNode r = queue. poll ( ) ; if ( l == null && r== null ) { continue ; } if ( l== null && r!= null ) { return false ; } if ( l!= null && r == null ) { return false ; } if ( l. val!= r. val) { return false ; } queue. offer ( l. left) ; queue. offer ( r. right) ; queue. offer ( l. right) ; queue. offer ( r. left) ; } return true ; }
}
3- ACM 实现
public class isSymmetric { public static 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; } } public static TreeNode build ( String str) { if ( str == null || str. length ( ) == 0 ) { return null ; } String input = str. replace ( "[" , "" ) ; input = input. replace ( "]" , "" ) ; String [ ] parts = input. split ( "," ) ; Integer [ ] nums = new Integer [ parts. length] ; for ( int i = 0 ; i < parts. length; i++ ) { if ( ! parts[ i] . equals ( "null" ) ) { nums[ i] = Integer . parseInt ( parts[ i] ) ; } else { nums[ i] = null ; } } Queue < TreeNode > queue = new LinkedList < > ( ) ; TreeNode root = new TreeNode ( nums[ 0 ] ) ; queue. offer ( root) ; int index = 1 ; while ( ! queue. isEmpty ( ) && index< parts. length) { TreeNode node = queue. poll ( ) ; if ( index< nums. length && nums[ index] != null ) { node. left = new TreeNode ( nums[ index] ) ; queue. offer ( node. left) ; } index++ ; if ( index< nums. length && nums[ index] != null ) { node. right = new TreeNode ( nums[ index] ) ; queue. offer ( node. right) ; } index++ ; } return root; } public static boolean isSymetric ( TreeNode root) { Queue < TreeNode > queue = new LinkedList < > ( ) ; queue. offer ( root. left) ; queue. offer ( root. right) ; while ( ! queue. isEmpty ( ) ) { TreeNode l = queue. poll ( ) ; TreeNode r = queue. poll ( ) ; if ( l== null && r== null ) { continue ; } if ( l!= null && r== null ) { return false ; } if ( l== null && r!= null ) { return false ; } if ( l. val!= r. val) { return false ; } queue. offer ( l. left) ; queue. offer ( r. right) ; queue. offer ( l. right) ; queue. offer ( r. left) ; } return true ; } public static void main ( String [ ] args) { Scanner sc = new Scanner ( System . in) ; String input = sc. nextLine ( ) ; TreeNode root = build ( input) ; System . out. println ( "结果是" + isSymetric ( root) ) ; } }