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
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } * 非递归的解法,可以用两个双端队列做层序遍历,然后队列从两端弹出元素,两端元素相等说明是对称 */ public class Solution { public boolean isSymmetricHelper(TreeNode r1, TreeNode r2) { //左右半支到叶子节点的时候 判断相等 if (r1 == null && r2 == null) return true; if (r1 == null && r2 != null) return false; if (r1 != null && r2 == null) return false; if (r1.val != r2.val) return false; //左半支的左子树 和右半支的右子树比较相等 左半支的右子树 和右半支的左子树比较相等 return isSymmetricHelper(r1.left, r2.right) && isSymmetricHelper(r1.right,r2.left); } public boolean isSymmetric(TreeNode root) { if (root==null){ return true; } if (root.left==null||root.right==null){ return root.left == root.right; } return isSymmetricHelper(root.left,root.right); } }