PTA playing with binary linked list (25 points) (traversal of binary tree)

7-9 Playing with a two-pronged linked list (25 points)

Design the program to create the binary linked list of the binary tree in the first order; then traverse the binary tree in the first order, middle order, and later order.

Input format:

Enter a binary tree in the first order. The key value of each node in the binary tree is represented by characters, and there are no spaces between the characters. Note that the empty tree information is also provided, and the # character represents an empty tree.

Output format:

Output 3 lines. The first line is the sequence of traversing the binary tree in the first order, the second line is the sequence of traversing the binary tree in the middle order, and the third line is the sequence of traversing the binary tree in postorder. No extra spaces are allowed at the beginning and end of each line. No # in the sequence.

Input sample:

ab##dc###

Sample output:

abdc
bacd
bcda

Problem solving

The title gives a pre-order traversal of a dfs tree.
For the interval [l, r], there is a split point k so that the tree can be transformed into l as the root [l + 1, k] as the left subtree, [k + 1 , r] is the right subtree. The key to this question is to find out the position of k.
Also use dfs to access the sequence.
Note that all trees are composed of letters and #. Now the # number is counted as the leaf node of the tree, then the letter is Are not leaf nodes, so there is the following relationship: the
number of leaf nodes (the number of'#') in the binary tree is b, and the number of non-leaf nodes (the number of letters) is a, and they satisfy

  • b = a + 1

So you can count the number of a and b. When he satisfies the above equation, it means that the k node is found, and then the binary tree traversal method is used to obtain the first-order, middle-order, and post-order traversals.

Code

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
const int maxn = 102;
string s;
string fron, mid, en;

void dfs(int k, int l, int r) {
    
    
	if(k >= s.size() || s[k] == '#') return;
	int a = 0, b = 0;
	for(int i = k + 1; i <= r; i++ ) {
    
    
		if(s[i] == '#')
			b++;
		else
			a++;
		if(b == a + 1)
			break;	
	}

	int rr = k + a + b;		//分界点
	fron += s[k];	//先序
	dfs(k + 1, k + 1, rr);
	mid += s[k];	//中序
	dfs(rr + 1, rr + 1, r);
	en += s[k];		//后序
}

int main() {
    
    
	cin >> s;
	dfs(0, 0, s.size() - 1);
	cout << fron << endl;
	cout << mid << endl;
	cout << en << endl;

	return 0;
}


Guess you like

Origin blog.csdn.net/qq_45349225/article/details/109786787