思路:
    通法就是递归,其他方法暂不考虑

    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. let result = 0
    15. let nodes = data => {
    16. if (data) {
    17. nodes(data.left)
    18. nodes(data.right)
    19. result++
    20. }
    21. }
    22. nodes(root)
    23. return result
    24. };

    image.png