我的js算法爬坑之旅-完全二叉树的节点个数

88 阅读1分钟

第四十八天:力扣第222题,完全二叉树的节点个数

地址:leetcode-cn.com/problems/co…

思路:深度优先遍历

var countNodes = function(root) {
  return root ? 1 + countNodes(root.left) + countNodes(root.right) : 0;
};

执行用时:120 ms, 在所有 JavaScript 提交中击败了75.00%的用户

内存消耗:56.6 MB, 在所有 JavaScript 提交中击败了36.60%的用户

其实展开是这样的:

var countNodes = function(root) {
  if (root === null)
  {
    return 0;
  }
  let left = root;
  let right = root;
  let lh = 0;
  let rh = 0;
  while(left)
  {
    lh ++;
    left = left.left;
  }
  while(right)
  {
    rh ++;
    right = right.right;
  }
  if (rh === lh)
  {
    return 2**rh - 1;
  }
  return 1 + countNodes(root.left) + countNodes(root.right);
};

执行用时:104 ms, 在所有 JavaScript 提交中击败了99.72%的用户

内存消耗:56.7 MB, 在所有 JavaScript 提交中击败了31.70%的用户