/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isBalanced = function (root) {
  if (!root) return true;
  if (Math.abs(findDepth(root.left) - findDepth(root.right)) > 1) return false;
  return isBalanced(root.left) && isBalanced(root.right);
};
const findDepth = (root) => {
  if (!root) return 0;
  return 1 + Math.max(findDepth(root.left), findDepth(root.right));
};
這題要判斷一個二元樹是否平衡。
平衡二元樹是一種每個節點的左右兩子樹高度差都不超過一的二元樹。
時間複雜度: O(n),每個節點最多訪問一次
空間複雜度: O(n)
LeetCode 110. Balanced Binary Tree
var levelOrder = function (root) {
  let queue = [root];
  let out = [];
  while (queue[0]) {
    const currQueueLength = queue.length;
    const layerNodes = [];
    for (let i = 0; i < currQueueLength; i++) {
      let cur = queue.shift();
      layerNodes.push(cur.val);
      if (cur.left) queue.push(cur.left);
      if (cur.right) queue.push(cur.right);
    }
    out.push(layerNodes);
  }
  return out;
};
使用 BFS + Queue 解題,每遍歷一層,將當前 queue 裡的節點取出,加入該節點的左、右子節點到 queue 裡面,遍歷完同層後,往下一層遍歷。
時間複雜度: O(n)
空間複雜度: O(n)
Binary Tree Level Order Traversal | Tree Breadth First Search 基礎概念 1 - Python - LeetCode 102
var lowestCommonAncestor = function (root, p, q) {
  if (root === null || root === p || root === q) return root;
  const left = lowestCommonAncestor(root.left, p, q);
  const right = lowestCommonAncestor(root.right, p, q);
  if (left !== null && right !== null) return root;
  return left !== null ? left : right;
};

要找出兩個節點的最小共同祖先,可以先分析出現最小共同祖先的情況,並找到 p 和 q 在哪:
時間複雜度: O(n)
空間複雜度: O(n)
贾考博 LeetCode 236. Lowest Common Ancestor of a Binary Tree 追本溯源 2
leetcode 中文 | Lowest Common Ancestor of a Binary Tree | Facebook 臉書考題 | Leetcode 236 | Python
Leetcode — 236. Lowest Common Ancestor of a Binary Tree (中文)