diff --git a/problems/0110.平衡二叉树.md b/problems/0110.平衡二叉树.md index 8a701bb3..90cb7336 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; +}; +``` + ## TypeScript ```typescript diff --git a/problems/面试题02.07.链表相交.md b/problems/面试题02.07.链表相交.md index dd91f069..2e7226de 100644 --- a/problems/面试题02.07.链表相交.md +++ b/problems/面试题02.07.链表相交.md @@ -224,12 +224,14 @@ var getIntersectionNode = function(headA, headB) { lenA = getListLen(headA), lenB = getListLen(headB); if(lenA < lenB) { + // 下面交换变量注意加 “分号” ,两个数组交换变量在同一个作用域下时 + // 如果不加分号,下面两条代码等同于一条代码: [curA, curB] = [lenB, lenA] [curA, curB] = [curB, curA]; [lenA, lenB] = [lenB, lenA]; } let i = lenA - lenB; while(i-- > 0) { - curA = curA.next + curA = curA.next; } while(curA && curA !== curB) { curA = curA.next;