文章
166
粉丝
68
获赞
855
访问
61.9k
#include <bits/stdc++.h>
using namespace std;
struct tnode{
char val;
struct tnode* left,* right;
tnode(char val):val(val),left(nullptr),right(nullptr){}
};
tnode* buildTree(string pre,int &index){
if(pre[index]=='#')return nullptr;
tnode* root=new tnode(pre[index]);
root->left=buildTree(pre,++index);
root->right=buildTree(pre,++index);
return root;
}
void countLeaf(tnode* root,int &ans){
if(root==nullptr)return;
if(root->left==nullptr&&root->right==nullptr)ans++;
countLeaf(root->left,ans);
countLeaf(root->right,ans);
}
int main(){
string s;
while(cin>>s){
int ans=0,index=0;
countLeaf(buildTree(s,index),ans);
cout<<ans<<endl;
}
}
先序字符串带#的类型的树生成规则就是先生成左子树,后生成右子树,遇到#的时候返回nullptr即可。
登录后发布评论
暂无评论,来抢沙发