第一种使用递归的方式:
public boolean isSymmetric(TreeNode root) { return check(root,root); } public boolean check(TreeNode t1,TreeNode t2){ if (t1==null && t2==null){ return true; } if(t1==null || t2==null){ return false; } return (t1.val==t2.val) && check(t1.right,t2.left) && check(t1.left,t2.right); }
第二种使用迭代的方式: public boolean isSymmetric(TreeNode root) { Queue<TreeNode> stack = new LinkedList<>();//定义一个栈;List 、 Deque、Cloneable; stack.add(root); stack.add(root);//root进栈; while (!stack.isEmpty()){ TreeNode t1=stack.poll();//出栈 TreeNode t2=stack.poll(); if(t1==null && t2==null) continue; if(t1==null || t2==null || t1.val!=t2.val) return false; stack.offer(t1.left);//t1.左子树进栈 stack.offer(t2.right);//t2.右子树进栈 stack.offer(t1.right); stack.offer(t2.left); } return true; }