From 7bda59c0623ff7f37f0bb4d67db44eede5b05543 Mon Sep 17 00:00:00 2001 From: h2linlin Date: Thu, 13 May 2021 20:52:01 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200101.=E5=AF=B9=E7=A7=B0?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0101.对称二叉树.md | 89 +++++++++++++++++++++++++++++++- 1 file changed, 88 insertions(+), 1 deletion(-) diff --git a/problems/0101.对称二叉树.md b/problems/0101.对称二叉树.md index 535300af..05a67623 100644 --- a/problems/0101.对称二叉树.md +++ b/problems/0101.对称二叉树.md @@ -254,7 +254,94 @@ public: ## 其他语言版本 Java: +```java +public class N0101 { + /** + * 解法1:DFS,递归。 + */ + public boolean isSymmetric2(TreeNode root) { + if (root == null) { + return false; + } + return compare(root.left, root.right); + } + + private boolean compare(TreeNode left, TreeNode right) { + if (left == null && right == null) { + return true; + } + if (left != null && right == null) { + return false; + } + if (left == null && right != null) { + return false; + } + + if (left.val == right.val) { + return compare(left.left, right.right) && compare(left.right, right.left); + } + + return false; + } + + /** + * 解法2:DFS,迭代 + */ + public boolean isSymmetric3(TreeNode root) { + if (root == null) { + return false; + } + + if (!equal(root.left, root.right)) { + return false; + } + + Deque st = new LinkedList<>(); + + st.push(root.right); + st.push(root.left); + + TreeNode curR = root.right; + TreeNode curL = root.left; + + while (!st.isEmpty()) { + curL = st.pop(); + curR = st.pop(); + + // 前序,处理 + if (!equal(curL, curR)) { + return false; + } + + if (curR != null && curL != null) { + st.push(curL.right); + st.push(curR.left); + st.push(curR.right); + st.push(curL.left); + } + } + + return true; + } + + private boolean equal(TreeNode l, TreeNode r) { + if (l == null && r == null) { + return true; + } + if (l != null && r == null) { + return false; + } + if (l == null && r != null) { + return false; + } + if (l.val == r.val) { + return true; + } + return false; + } +} +``` Python: @@ -283,4 +370,4 @@ const check = (leftPtr, rightPtr) => { * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) -
\ No newline at end of file +