来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/symmetric-tree
题意:
给你一个二叉树的根节点 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
进阶:你可以运用递归和迭代两种方法解决这个问题吗?
思路:
这道题分递归法和迭代法(迭代法这里用双端队列来做)来做,原理都是一样的,主要是比较根节点的左右儿子所形成的左右子树是否是对称的,这时候是要看内侧和外侧之分,详情看参考文章吧
递归法 Java代码:
class Solution {
private boolean compare(TreeNode left, TreeNode right) {
if (left == null && right == null)
return true;
else if (left == null || right == null || left.val != right.val)
return false;
return compare(left.left, right.right) && compare(left.right, right.left);
}
public boolean isSymmetric(TreeNode root) {
return compare(root.left, root.right);
}
}
迭代法 Java代码:
class Solution {
public boolean isSymmetric(TreeNode root) {
Deque<TreeNode> deque = new LinkedList<>();
deque.offerFirst(root.left);
deque.offerLast(root.right);
while (!deque.isEmpty()) {
TreeNode left = deque.pollFirst();
TreeNode right = deque.pollLast();
if (left == null && right == null)
continue;// 注意这里是continue,不是return true,要跟递归法区分
else if (left == null || right == null || left.val != right.val)
return false;
deque.offerFirst(left.left);
deque.offerLast(right.right);
deque.offerFirst(left.right);
deque.offerLast(right.left);
}
return true;
}
}