Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1/ \2 2/ \ / \3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1/ \2 2\ \3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
题意
判断一个树是否关于中心轴对称。
思路
递归或利用队列迭代来判断。
代码实现 - 迭代
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/class Solution {public boolean isSymmetric(TreeNode root) {if (root == null) {return true;}// 如果以两个root作为递归起点则会导致接下来的每个点都被访问2次return isSymmetric(root.left, root.right);}private boolean isSymmetric(TreeNode x, TreeNode y) {if (x == null && y == null) {return true;} else if (x == null || y == null || x.val != y.val) {return false;} else {return isSymmetric(x.left, y.right) && isSymmetric(x.right, y.left);}}}
代码实现 - 迭代
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/class Solution {public boolean isSymmetric(TreeNode root) {if (root == null) {return true;}// 注意不能使用ArrayDeque,因为ArrayDeque不能插入nullQueue<TreeNode> q = new LinkedList<>();// 如果插入两个root则会导致接下来的每个点都入队了2次q.offer(root.left);q.offer(root.right);while (!q.isEmpty()) {TreeNode x = q.poll();TreeNode y = q.poll();if (x == null && y == null) {continue;} else if (x == null || y == null || x.val != y.val) {return false;} else {q.offer(x.left);q.offer(y.right);q.offer(x.right);q.offer(y.left);}}return true;}}
