2011百度实习生面试题-二叉树“弓”字形遍历

题目描述:对二叉树进行“弓”字形遍历,即第一层从左往右遍历,第二层从右往左遍历,第三层从左往右遍历.....

思路:传统的广度优先遍历,只需一个队列即可,但只能实现每层从左往右遍历。这里可以设两个栈,分别存放相邻两层的节点,先将某层节点存入一个栈,对这个栈的每个节点进行访问和出栈操作,在出栈的同时把它的孩子节点存入另一个栈,当这层的每个节点都操作完毕后,同时也实现了下一层节点在另一个栈的入栈操作。要注意的是,相邻两层的节点入栈的顺序是相反的,这样才能实现“弓”字形遍历。

 

代码如下:

typedef struct BiTNode{        
	ElemType data;        
	struct BiTNode *left;        
	struct BiTNode *right;}BiTNode, *BiTree;

void baidu_Traverse(BiTree T)
{ 
	BiTree stack1[100], stack2[100];     
	BiTree *curstack, *otherstack;       
	BiTree p;    
	int top1 = 0, top2 = 0;  
	int curtop, othertop;  
	int flag = 0, temp, res;        
	//根节点入栈        
	stack1[top1++] = T;        
	//当前操作栈为stack1,另一个栈为stack2        
	curstack = stack1;     
	otherstack = stack2;  
	curtop = top1;  
	othertop = top2;        
	//遍历当前站     
	while(curtop >= 1){     
		curtop--;      
		p = curstack[curtop];                
		//访问当前栈的顶点元素      
		printf("%c /n", curstack[curtop]->data);             
		//flag用来控制每一层的入栈顺序,第二层从左到右             
		//第三层从右到做,以此类推,初始值设为从左到右(第二层)            
		if(flag == 0){                        
			if(p->left){ 
				otherstack[othertop++] = p->left;     
			}       
			if(p->right){     
				otherstack[othertop++] = p->right;     
			}      
		}else{           
			if(p->right){   
				otherstack[othertop++] = p->right;        
			} 
			if(p->left){
				otherstack[othertop++] = p->left;      
			}  
		}  
		//如果当前栈的元素全部操作完毕        
		if(curtop <= 0){                   
			//当前栈变为另外那个栈       
			curstack  = (curstack == stack1)?stack2:stack1;      
			otherstack = (otherstack == stack1)?stack2:stack1;    
			//交换curtop和othertop       
			temp = curtop;   
			curtop = othertop;     
			othertop = temp;   
			//通过判断处于二叉树的第几层,来决定元素的入栈顺序        
			double value = log((double)curtop)/log((double)2); 
			res = (int)value;       
			if(res % 2 == 0)               
				flag = 0;       
			else                                
				flag = 1;                
		}        
	}
}


 

这里使用两个栈来做,如果使用双端栈的话,也可以模拟两个栈。一篇介绍双端栈的博客http://hi.baidu.com/ilotus_y/blog/item/eeeddd603e4ed443eaf8f82a.html

你可能感兴趣的:(2011百度实习生面试题-二叉树“弓”字形遍历)