简单思路:直接 DFS 计算就好了,当然这题目是完全二叉树,有更好的计算方式
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var countNodes = function (root) {
if (!root) return 0;
return 1 + countNodes(root.left) + countNodes(root.right);
};