From be6c45c636556b1c0d3838f265fe7830ca4f00ff Mon Sep 17 00:00:00 2001 From: jobinben <1021137079@qq.com> Date: Sun, 6 Feb 2022 19:06:51 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=200110.=E5=B9=B3=E8=A1=A1?= =?UTF-8?q?=E4=BA=8C=E5=8F=89=E6=A0=91.md=20JavaScript=E8=AF=AD=E8=A8=80?= =?UTF-8?q?=E7=89=88=E6=9C=AC=E7=9A=84=E8=BF=AD=E4=BB=A3=E8=A7=A3=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0110.平衡二叉树.md | 45 +++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 9d43407a..8a11c013 100644 --- a/problems/0110.平衡二叉树.md +++ b/problems/0110.平衡二叉树.md @@ -604,7 +604,8 @@ func abs(a int)int{ } ``` -## JavaScript +## JavaScript +递归法: ```javascript var isBalanced = function(root) { //还是用递归三部曲 + 后序遍历 左右中 当前左子树右子树高度相差大于1就返回-1 @@ -627,6 +628,48 @@ var isBalanced = function(root) { }; ``` +迭代法: +```javascript +// 获取当前节点的高度 +var getHeight = function (curNode) { + let queue = []; + if (curNode !== null) queue.push(curNode); // 压入当前元素 + let depth = 0, res = 0; + while (queue.length) { + let node = queue[queue.length - 1]; // 取出栈顶 + if (node !== null) { + queue.pop(); + queue.push(node); // 中 + queue.push(null); + depth++; + node.right && queue.push(node.right); // 右 + node.left && queue.push(node.left); // 左 + } else { + queue.pop(); + node = queue[queue.length - 1]; + queue.pop(); + depth--; + } + res = res > depth ? res : depth; + } + return res; +} +var isBalanced = function (root) { + if (root === null) return true; + let queue = [root]; + while (queue.length) { + let node = queue[queue.length - 1]; // 取出栈顶 + queue.pop(); + if (Math.abs(getHeight(node.left) - getHeight(node.right)) > 1) { + return false; + } + node.right && queue.push(node.right); + node.left && queue.push(node.left); + } + return true; +}; +``` + ## C 递归法: ```c