解法:
c语言
#include<iostream>
#include<vector>
using namespace std;
typedef struct tNodes{char val;tNodes* left, * right;
}* tNode;void creat(tNode& t) {char ch;cin >> ch;if (ch == '#') t= NULL;else {t = new tNodes;t->val = ch;creat(t->left);creat(t->right);}
}
void dfs(tNode& t,char x) {if (t == NULL) return;if (t->val == x){int cnt = 0;if (t->left) cnt++;if (t->right) cnt++;cout << cnt;return;}dfs(t->left, x);dfs(t->right, x);
}
int main(){tNode root;creat(root);char x;cin >> x;dfs(root, x);return 0;
}
c++
#include<iostream>
using namespace std;
struct treeNode {char val;treeNode* left;treeNode* right;treeNode(char x) :val(x), left(NULL), right(NULL) {};
};
treeNode* buildtree() {char ch;cin >> ch;if (ch == '#') return NULL;treeNode* root = new treeNode(ch);root->left = buildtree();root->right = buildtree();return root;
}
void dfs(treeNode* root, char x) {if (root == NULL) return;if (root->val == x) {int cnt = 0;if (root->left) cnt++;if (root->right) cnt++;cout << cnt;return;}dfs(root->left, x);dfs(root->right, x);
}
int main() {treeNode* root = buildtree();char x;cin >> x;dfs(root, x);return 0;
}