101. 对称二叉树
给你一个二叉树的根节点 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.com/problems/symmetric-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
分析
方法一:迭代
将左子树和右子树的根(叶子节点)按照镜像位置存储到队列中,每次取出前两个进行比较,比较通过就继续存储当前两个的镜像节点,直到比较失败返回false或者比较全部成功返回true。
方法二:递归
新建一个用于递归的方法,该方法传入参数为root,root,后续每次传入的参数为当前传入参数的两个镜像节点,最后取交集即可
更详细的分析可以参考:
https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0101.%E5%AF%B9%E7%A7%B0%E4%BA%8C%E5%8F%89%E6%A0%91.md
题解(Java)
方法一:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root.left);
q.offer(root.right);
while (!q.isEmpty()) {
TreeNode l = q.poll(), r = q.poll();
if (l == null && r == null) continue;
if ((l == null || r == null) || l.val != r.val) return false;
q.offer(l.left);
q.offer(r.right);
q.offer(l.right);
q.offer(r.left);
}
return true;
}
}
方法二:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
return check(root, root);
}
public boolean check(TreeNode l, TreeNode r) {
if (l == null && r == null) return true;
if (l == null || r == null) return false;
return l.val == r.val && check(l.left, r.right) && check(l.right, r.left);
}
}