美文网首页
222. Count Complete Tree Nodes

222. Count Complete Tree Nodes

作者: jluemmmm | 来源:发表于2021-10-15 12:50 被阅读0次

完全二叉树的节点的个数。

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

完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。

递归

  • 时间复杂度O(n),空间复杂度O(logn)
  • Runtime: 104 ms, faster than 81.00%
  • Memory Usage: 58.3 MB, less than 72.04%
/**
 * 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 {number}
 */
var countNodes = function(root) {
  return !root ? 0 : countNodes(root.left) + countNodes(root.right) + 1;
};

二分法

  • 时间复杂度O(logn^2),空间复杂度O(1)
  • Runtime: 96 ms, faster than 95.34%
  • Memory Usage: 58.3 MB, less than 59.86%
/**
 * 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 {number}
 */
var countNodes = function(root) {
  if (!root) return 0;
  let level = computeDepth(root);
  if (level === 0) return 1;
  let left = 1;
  let right = Math.pow(2, level) - 1;
  let flag;
  while (left <= right) {
    flag = parseInt((left + right) / 2);
    if (exists(flag, level, root)) {
      left = flag + 1;
    } else {
      right = flag - 1;
    }
  }
  return Math.pow(2, level) - 1 + left;
};

var computeDepth = function (root) {
  let level = 0;
  while (root.left) {
    root = root.left;
    level++;
  }
  return level;
}

var exists = function (index, depth, node) {
  let left = 0;
  let right = Math.pow(2, depth) - 1;
  let flag;
  for (let i = 0; i < depth; i++) {
    flag = parseInt((left + right) / 2);
    if (index <= flag) {
      node = node.left;
      right = flag;
    } else {
      node = node.right;
      left = flag + 1;
    }
  }
  return node !== null;
}

相关文章

网友评论

      本文标题:222. Count Complete Tree Nodes

      本文链接:https://www.haomeiwen.com/subject/kvhkoltx.html