import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { public boolean isSymmetric (TreeNode root) { if(root == null) { return true; } // return isSymmetricRecursion(root.left, root.right); return isSymmetricIteration(root); } // 递归法 private boolean isSymmetricRecursion(TreeNode nodeOne, TreeNode nodeTwo) { if(nodeOne == null && nodeTwo == null) { return true; } if(nodeOne == null || nodeTwo == null || nodeOne.val != nodeTwo.val) { return false; } return isSymmetricRecursion(nodeOne.left, nodeTwo.right) && isSymmetricRecursion(nodeOne.right, nodeTwo.left); } // 迭代法 private boolean isSymmetricIteration(TreeNode root) { Queue<TreeNode> queue = new LinkedList(); queue.add(root.left); queue.add(root.right); while(!queue.isEmpty()) { TreeNode leftNode = queue.remove(); TreeNode rightNode = queue.remove(); if(leftNode == null && rightNode == null) { continue; } if(leftNode == null || rightNode == null || leftNode.val != rightNode.val) { return false; } queue.add(leftNode.left); queue.add(rightNode.right); queue.add(leftNode.right); queue.add(rightNode.left); } return true; } }