From 058f64624a062083aeb78ea5589c6e22ce444a12 Mon Sep 17 00:00:00 2001 From: wang2jun <91008685+wang2jun@users.noreply.github.com> Date: Fri, 19 Aug 2022 10:42:17 +0800 Subject: [PATCH] =?UTF-8?q?0100=E7=9B=B8=E5=90=8C=E7=9A=84=E6=A0=91=20?= =?UTF-8?q?=E5=A2=9E=E5=8A=A0=20js=20=E8=BF=AD=E4=BB=A3=E6=B3=95=E7=89=88?= =?UTF-8?q?=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0100.相同的树.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/problems/0100.相同的树.md b/problems/0100.相同的树.md index 4b6eb7aa..9820173d 100644 --- a/problems/0100.相同的树.md +++ b/problems/0100.相同的树.md @@ -253,6 +253,28 @@ var isSameTree = function (p, q) { return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }; ``` +> 迭代法 + +```javascript +var isSameTree = (p, q) => { + const queue = [{ p, q }]; + // 这是用{ } 解决了null的问题! + while (queue.length) { + const cur = queue.shift(); + if (cur.p == null && cur.q == null) continue; + if (cur.p == null || cur.q == null) return false; + if (cur.p.val != cur.q.val) return false; + queue.push({ + p: cur.p.left, + q: cur.q.left + }, { + p: cur.p.right, + q: cur.q.right + }); + } + return true; +}; +``` TypeScript: