From fd249932b0501a2ddc4780ea7e2f39199ca91c34 Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Wed, 15 Jul 2020 09:15:03 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E4=BA=8C=E5=8F=89=E6=A0=91=E7=9B=B8?= =?UTF-8?q?=E5=85=B3.md?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Algorithm/剑指 Offer/二叉树相关.md | 59 +++++++++++++++++++ 1 file changed, 59 insertions(+) diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index f87ff62..cc05e89 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/blogs/Algorithm/剑指 Offer/二叉树相关.md @@ -425,3 +425,62 @@ public class Codec { } ``` +#### [28. 对称的二叉树](https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof/) + +```java +class Solution { + + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return true; + } + return helper(root.left, root.right); + } + + private boolean helper(TreeNode root1, TreeNode root2) { + if (root1 == null && root2 == null) { + return true; + } + if (root1 == null || root2 == null) { + return false; + } + if (root1.val != root2.val) { + return false; + } + return helper(root1.left, root2.right) && helper(root1.right, root2.left); + } +} +``` + +```java +class Solution { + + public boolean isSymmetric(TreeNode root) { + if (root == null) { + return true; + } + Deque queue = new LinkedList<>(); + queue.addFirst(root.left); + queue.addLast(root.right); + while (!queue.isEmpty()) { + TreeNode first = queue.removeFirst(); + TreeNode last = queue.removeLast(); + if (first == null && last == null) { + continue; + } + if (first == null || last == null) { + return false; + } + if (first.val != last.val) { + return false; + } + queue.addFirst(first.right); + queue.addFirst(first.left); + queue.addLast(last.left); + queue.addLast(last.right); + } + return true; + } +} +``` +