package Struct; public class TreeNode { public int val = 0; public TreeNode left = null; public TreeNode right = null; public TreeNode(int val) { this.val = val; } @Override public String toString() { return "TreeNode [val=" + val + ", left=" + left + ", right=" + right + "]"; } }
1 package offer; 2 3 import Struct.TreeNode; 4 /** 5 * 6 * 二叉树的镜像定义:源二叉树 7 8 8 / \ 9 6 10 10 / \ / \ 11 5 7 9 11 12 13 5 6 7 8 9 10 11 14 镜像二叉树 15 8 16 / \ 17 10 6 18 / \ / \ 19 11 9 7 5 20 11 10 9 8 7 6 5 21 * @author 爱不会绝迹 22 * 23 * 24 * 请实现一个函数,用来判断一颗二叉树是不是对称的。 25 * 注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。 26 * 27 */ 28 public class Problem38 { 29 30 public static boolean isSymmetrical(TreeNode pRoot) { 31 if(pRoot==null){ 32 return true; 33 } 34 return isMirror(pRoot.left,pRoot.right); 35 } 36 37 public static boolean isMirror(TreeNode left,TreeNode right){ 38 if(left==null&&right==null){ 39 return true; 40 } 41 if(left==null || right==null){ 42 return false; 43 } 44 return left.val==right.val&&isMirror(left.left,right.right)&&isMirror(left.right,right.left); 45 } 46 47 private static int index = -1; 48 public static void main(String[] args) { 49 Integer[] array = {5,3,3,4,null,null,4,2,null,null,2,1,null,null,1}; 50 TreeNode tree = createBinTree(array); 51 boolean b = isSymmetrical(tree); 52 System.out.println(b); 53 } 54 private static TreeNode createBinTree(Integer[] array) { 55 TreeNode tree = null; 56 if(index < array.length-1 && array[++index]!=null){ 57 tree = new TreeNode(array[index]); 58 tree.left = createBinTree(array); 59 tree.right = createBinTree(array); 60 } 61 return tree; 62 } 63 }