题目:
解答:
最简单的解决方法就是用递归一个一个的计算节点。
时间复杂度为O(N);
空间复杂度为O(d)=O(logN);
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 int countNodes(TreeNode* root) 13 { 14 if (NULL == root) 15 { 16 return 0; 17 } 18 19 return 1 + countNodes(root->left) + countNodes(root->right); 20 } 21 };