当前位置:网站首页>Expression tree - medium order printout

Expression tree - medium order printout

2022-06-13 00:48:00 Feiyichai

Give an expression tree , Output the middle order expression , You need parentheses to prioritize ( It looks like it is. 408 The real question , I feel I haven't learned recursion well , It can only be realized by stack , I don't know , Ask God for correction )

 Insert picture description here

The expression shown in the figure , Output is (a+(b*(-d)-(e/f))

  1. Algorithm analysis
    ( One ) If the current node is a leaf node on the left subtree , Output left parenthesis and data
     Insert picture description here
    ( Two ) If the current node is the root node, output data directly
     Insert picture description here
    ( 3、 ... and ) If the current node has a right subtree but the left subtree is empty , Then the left bracket and root node data are output
     Insert picture description here
    ( Four ) If the current node is a leaf node on the right subtree , Output right parentheses and data
     Insert picture description here
  2. Code implementation
// The idea of non recursive middle order traversal 
void print(Bitree T){
    
	if(!T) return ;// Tree is empty exit function 
	Stack s;		// Declare a stack 
	BiTNode *p=T;
	int flag=1;		// The flag that determines whether the current subtree is on the left or right 
	print('(');
	while(p||!IsEmpty(s)){
    	// The current node is not empty or the stack is not empty 
		if(p){
    
			push(s,p);   // Zuozi tree is not empty , Continue to traverse the left subtree 
			p=p->lchild;
			flag=1;  // Flag that the current traversal is the left subtree 
		}
		else{
    	//  Left to the bottom 
			pop(s,p);// Out of the stack ;
			if((!p->lchild&&!p->rchild&&flag))||(!p->lchild&&p->rchild)){
    // The first and fourth cases 
				print('(');
				print(p->data);
			}
			else if(p->lchild&&p->rchild)// The second case 
				print(p->data);
			else if(!flag){
    // The third case 
				print(')');
				print(p->data);
			}
			p=p->rchild;// Go right after judgment 
			flag=0;
		}//while
		print(')');
	}//print 
原网站

版权声明
本文为[Feiyichai]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280559017063.html