解法:
#include<iostream>
#include<queue>
using namespace std;
// 定义二叉树结点
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) :val(x), left(NULL), right(NULL) {};
};
// 先序递归遍历建立二叉树
TreeNode* buildTree() {
char c;
cin >> c;
if (c == '#') {
return NULL;
}
TreeNode* root = new TreeNode(c);
root->left = buildTree();
root->right = buildTree();
return root;
}
int dfs(TreeNode* root) {
if (root == NULL) return 0;
if (root->left==NULL&&root->right==NULL) return 1;
int left = dfs(root->left);
int right = dfs(root->right);
return left + right;
}
int main() {
TreeNode* root= buildTree();
cout<<dfs(root);
return 0;
}