題目:
給定一棵完全二元樹,請計算這棵樹的節點總數。
使用 DFS 遞迴方式來計數,
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
return dfs(root);
}
private:
int dfs(TreeNode* root) {
if (root == nullptr)
return 0;
return 1 + dfs(root->left) + dfs(root->right);
}
};
參考:
#222. Count Complete Tree Nodes