给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3]
是对称的。
此题与上一题有异曲同工之妙,[LeetCode] #100 相同的树
思路基本一样,递归解法
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public boolean isSymmetric(TreeNode root) { return check(root, root); } public boolean check(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null || q == null) return false; return p.val == q.val && check(p.left, q.right) && check(p.right, q.left); } }
非递归解法
class Solution { public boolean isSymmetric(TreeNode root) { TreeNode l = root.left,r = root.right; Queue<TreeNode> tmpQueue = new LinkedList<TreeNode>(); tmpQueue.offer(l); tmpQueue.offer(r); while(!tmpQueue.isEmpty()){ l = tmpQueue.poll(); r = tmpQueue.poll(); if(l == null && r == null){ continue; } if((l == null || r == null) || l.val != r.val){ return false; } tmpQueue.offer(l.left); tmpQueue.offer(r.right); tmpQueue.offer(l.right); tmpQueue.offer(r.left); } return true; } }
知识点:无
总结:无