给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
递归:深度优先遍历
- 对于每个节点,先去计算他的子节点的个数,直到叶子节点
- 叶子节点的子节点数量为0,他本身以及子节点总数量为1
function countNodes(root: TreeNode | null): number {
if (root === null) return 0
return countNodes(root.left) + countNodes(root.right) + 1
}
队列:广度优先遍历
- 先判断当前节点是否有子节点,如果有将他们入队
- 然后将队首节点出队,计数,继续判断是否有子节点
- 继续出对,计数。。。
- 直到队内无元素,统计结束
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
}