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

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

    示例 1:
    image.png
    输入:root = [1,2,3,4,5,6]
    输出:6
    示例 2:

    输入:root = []
    输出:0
    示例 3:

    输入:root = [1]
    输出:1

    1. /**
    2. * Definition for a binary tree node.
    3. * function TreeNode(val, left, right) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.left = (left===undefined ? null : left)
    6. * this.right = (right===undefined ? null : right)
    7. * }
    8. */
    9. /**
    10. * @param {TreeNode} root
    11. * @return {number}
    12. */
    13. var countNodes = function (root) {
    14. if (!root) return 0
    15. // 棵完全二叉树的两棵子树,至少有一棵是满二叉树,通过树高计算
    16. let leftRoot = root, rightRoot = root;
    17. let leftHight = 0, rightHight = 0;
    18. // 分别记录左右子树高度
    19. while (leftRoot !== null) {
    20. leftRoot = leftRoot.left;
    21. leftHight += 1;
    22. }
    23. while (rightRoot !== null) {
    24. rightRoot = rightRoot.right;
    25. rightHight += 1;
    26. }
    27. // 如果高度相同,则是一颗满二叉树
    28. if (leftHight === rightHight) {
    29. return Math.pow(2, leftHight) - 1;
    30. }
    31. // 不同按照普通高度计算 =====================================
    32. return countNodes(root.left) + countNodes(root.right) + 1
    33. };

    image.png