给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
提示:
树中节点数目在范围 [1, 1000] 内
-100 <= Node.val <= 100
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
class Solution {
public boolean isSymmetric(TreeNode root) {
return dfs(root.left, root.right);
}
private boolean dfs(TreeNode left, TreeNode right) {
if (left == null && right != null || left != null && right == null) return false;
if (left == null && right == null) return true;
if (left.val != right.val) return false;
return dfs(left.left, right.right) && dfs(left.right, right.left);
}
}
迭代
class Solution {
public boolean isSymmetric(TreeNode root) {
Deque<TreeNode> q = new LinkedList<>();
q.addLast(root.left);
q.addLast(root.right);
while (!q.isEmpty()) {
TreeNode a = q.pollFirst();
TreeNode b = q.pollFirst();
if (a == null && b != null || a != null && b == null) return false;
if (a == null && b == null) continue;
if (a.val != b.val) return false;
q.addLast(a.left);
q.addLast(b.right);
q.addLast(a.right);
q.addLast(b.left);
}
return true;
}
}