文章

33

粉丝

0

获赞

155

访问

5.8k

头像
二叉树叶结点的个数 题解:结构体
P4777
发布于2026年3月21日 23:17
阅读数 205

没招了,想了一下这种无序的不太好模拟。还是直接结构体建树然后直接遍历吧。

#include <bits/stdc++.h>
using namespace std;

struct Node{
	char val;
	Node* l;
	Node* r;
};

Node* newNode(char val){
	Node* node = new Node;
	node->val = val;
	node->l = nullptr;
	node->r = nullptr;
	
	return node;
}

int cnt=0;
int idx = 0;
string s;

void first_visit(Node* head){//先序,
	if(head==nullptr) return;
	
	if(head->l==nullptr && head->r==nullptr) cnt++;
	first_visit(head->l);
	first_visit(head->r);
}

Node* build(){//递归建树 
	if(idx>=s.size()) return nullptr;
	
	char c = s[idx++];
	if(c=='#' ) return nullptr;
	
	Node* node = newNode(c);
	node->l = build();
	node->r = build();
	
	return node;
}

int main() {

    while(getline(cin,s)){
    	Node* root = build();
    	first_visit(root);
    	cout<<cnt<<endl;
    	cnt=0;
	}

    return 0;
}

 

 

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发