视频分享地址: https://space.b|

明月照江江

园龄:7年4个月粉丝:34关注:0

📂算法
🔖算法
2023-09-11 08:33阅读: 9评论: 0推荐: 0

leetcode - 对称二叉树

给你一个二叉树的根节点 root , 检查它是否轴对称。

示例 1:
image

输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:

image

输入:root = [1,2,2,null,3,null,3]
输出:false

解法思路

也是递归的思想

  1. 检查当前两个节点是否为null,是,则说明到最后了,可以返回判断结果了
  2. 两个节点都不是null,则左节点的右左子节点与右节点的右子节点比较,另一边同理。
/**
 * 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 static List<TreeNode> queue = new LinkedList<TreeNode>();

    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return false;
        }

        return isMirrorTree(root.left, root.right);
    }

    public boolean isMirrorTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        }

        if (p == null || q == null) {
            return false;
        }

        if (p.val != q.val) {
            return false;
        }

        return isMirrorTree(p.left, q.right) && isMirrorTree(p.right, q.left);
    }
}

本文作者:明月照江江

本文链接:https://www.cnblogs.com/gradyblog/p/17692539.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   明月照江江  阅读(9)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起