Programming Title: The number of leaf nodes of binary tree (directed to the front in order traversal, contribution, the number of leaf nodes)

The number of leaf nodes in a binary list storage structure as a binary tree, the binary tree.

Input formats:

Motif sequence input to the binary tree.

Tip: a binary sequence of first order is a string, if the character is a '#', it indicates that the binary tree is empty, otherwise, the character is a data element corresponding node.

Output formats:

There are two output lines:

The first row is the binary sequence preorder;

The second line is the number of leaf nodes of the binary tree.

Sample input:

ABC##DE#G##F###

Sample output:

CBEGDFA

3

 

#include<iostream>
#include<stack>
#include<string>
using namespace std;
int a[10000],cunt=0;
void mid(int k=1){
	if(a[k*2]!=-1)mid(k*2);
	cout<<(char)a[k];
	if(a[k*2+1]!=-1)mid(k*2+1);   //中序遍历 
	
	if(a[k*2]==-1&&a[k*2+1]==-1)cunt++;   //增加叶子节点个数 
}
int main() {
	string str;
	stack<int> s;
	cin>>str;
	s.push(1);
	for(int i=0; i<str.length(); i++) {  //根据前序遍历特点进行建树 
		int p=s.top();s.pop();
		if(str[i]!='#') {
			a[p]=str[i];
			s.push(p*2+1);
			s.push(p*2);
		} else a[p]=-1;
	}
	mid();cout<<endl<<cunt<<endl;
	return 0;
}

 

Published 42 original articles · won praise 16 · views 3413

Guess you like

Origin blog.csdn.net/qq_41542638/article/details/95361138