一日一练: 完全二叉树的节点个数

162 阅读1分钟

给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。

递归:深度优先遍历

  1. 对于每个节点,先去计算他的子节点的个数,直到叶子节点
  2. 叶子节点的子节点数量为0,他本身以及子节点总数量为1
function countNodes(root: TreeNode | null): number {
  if (root === null) return 0
  // 递归计算子节点
  // +1 是将当前节点加入计数
  return countNodes(root.left) + countNodes(root.right) + 1
}

队列:广度优先遍历

  1. 先判断当前节点是否有子节点,如果有将他们入队
  2. 然后将队首节点出队,计数,继续判断是否有子节点
  3. 继续出对,计数。。。
  4. 直到队内无元素,统计结束
function countNodes(root: TreeNode | null): number {
  if (root === null) return 0
  const arr = [root]
  let count = 0
  while (arr.length) {
    // 出队
    const top = arr.shift() as TreeNode
    // 计数
    count++
    top.left && arr.push(top.left)
    top.right && arr.push(top.right)
  }
  // 节点总数量
  return count
}