给定一棵二叉树,判断琪是否是自身的镜像(即:是否对称)两种方法递归与迭代
判断二叉树是否对称
http://www.nowcoder.com/questionTerminal/1b0b7f371eae4204bc4a7570c84c2de1
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return bool布尔型 */ public boolean isSymmetric(TreeNode root) { return checkMetric(root, root); } private boolean checkMetric(TreeNode root1, TreeNode root2) { if (root1 == null && root2 == null) return true; if ((root1 != null && root2 == null) || root1 == null && root2 != null) return false; return (root1.val == root2.val && checkMetric(root1.left, root2.right) && checkMetric(root1.right, root2.left)); } } // 非递归,利用层次遍历,但是要注意左右入队次序; if (root == null) return true; Queue<TreeNode> queue = new LinkedList<TreeNode>(); if (root.left == null || root.right == null) { return root.left == root.right; } queue.add(root.left); queue.add(root.right); while (queue.size() > 0) { TreeNode lefTreeNode = queue.poll(); TreeNode rigtheTreeNode = queue.poll(); if ((lefTreeNode == null && rigtheTreeNode != null) || (lefTreeNode != null && rigtheTreeNode == null)) { return false; } else if (lefTreeNode == null && rigtheTreeNode == null) { continue; } else if (lefTreeNode.val != rigtheTreeNode.val) { return false; } queue.add(lefTreeNode.left); queue.add(rigtheTreeNode.right); queue.add(lefTreeNode.right); queue.add(rigtheTreeNode.left); } return true; }