題目原型:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3基本思路:
根據例子我們發現,每一層,給定兩個指針分別從左端和右端開始,只有當左端的左子樹的值等於右端的右子樹的值,並且左端的右子樹的值等於右端左子樹的值時,此樹便稱為中心對稱樹(Symmetric Tree)。
public boolean isSymmetric(TreeNode root) { if(root==null) return true; ArrayList list = new ArrayList(); list.add(root); boolean isFirst = true; while(list.size()>0) { if(list.size()%2==1&&isFirst==false) return false; for(int i = 0,j=list.size()-1;i<=j;i++,j--) { TreeNode one = list.get(i); TreeNode two = list.get(j); if(one.left!=null&&two.right!=null) { if(one.left.val!=two.right.val) return false; } if(one.right!=null&&two.left!=null) { if(one.right.val!=two.left.val) return false; } if((one.left==null&&two.right!=null)||(one.left!=null&&two.right==null)) return false; } //加入下一層節點 int size = list.size(); while(size>0) { if(list.get(0).left!=null) list.add(list.get(0).left); if(list.get(0).right!=null) list.add(list.get(0).right); list.remove(0); size--; } isFirst = false;//表示不是第一層了 } return true; }