Skip to content

完全二叉树的节点个数

LeetCode-222

js
// BFS 
var countNodes = function(root) {
  if(root === null) return 0
  let q = [root]
  let res = 0
  while(q.length) {
    let len = q.length
    for(let i = 0; i < len; i++) {
      res++
      const node = q.shift()
      if(node.left) q.push(node.left)
      if(node.right) q.push(node.right)
    }
  }
  return res
}

// DFS
var countNodes = function(root) {
  if(root === null) return 0
  let leftCount = countNodes(root.left)
  let rightCount = countNodes(root.right)
  return leftCount + rightCount + 1
}