给你一个二叉树的根节点 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
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/symmetric-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public boolean isSymmetric(TreeNode root) {
// return isSymmetricI(root);
return isSymmetricII(root);
}
//方法二:迭代,先将root的左右子树添加到队列
//然后从队列中取出两个节点left和right进行比较
//最后将left的左子树和right的右子树,left的右子树和right的左子树 添加到队列
//时间和空间复杂度O(N)
private boolean isSymmetricII(TreeNode root) {
if (root == null) {
return true;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root.left);
queue.offer(root.right);
while (!queue.isEmpty()) {
TreeNode left = queue.poll();
TreeNode right = queue.poll();
if (left == null && right == null) {
continue;
}
if (left == null || right == null) {
return false;
}
if (left.val != right.val) {
return false;
}
queue.offer(left.left);
queue.offer(right.right);
queue.offer(left.right);
queue.offer(right.left);
}
return true;
}
//根据题意可以发现如下规律:
//root左子树的左节点等于root右子树的右节点
//root左子树的右节点等于root右子树的左节点
//方法一:递归,时间和空间复杂度O(N)
private boolean isSymmetricI(TreeNode root) {
if (root == null) {
return true;
}
return traverse(root.left, root.right);
}
private boolean traverse(TreeNode left, TreeNode right) {
if (left == null && right == null) {
return true;
}
if (left == null || right == null) {
return false;
}
if (left.val != right.val) {
return false;
}
return traverse(left.left, right.right) && traverse(left.right, right.left);
}
}