打印二叉树中节点的所有祖先

题目:在1棵二叉树中,假设所有节点的值都不同,给定值x,打印值为x的节点的所有祖先节点

解: 利用后续非递归遍历打印。后续非递归遍历中,当节点2次进栈2次出栈后要访问它,此时根据后续遍历性质,它的左右孩子都被访问过了,访问过这个节点后再下一个要访问的节点就是当前节点的父节点。代码如下

/*
	 *后序遍历
 */

#include<iostream>
#include<cstdlib>
using namespace std;

typedef char Elemtype;
typedef struct node
{
	Elemtype data;
	struct node* left;
	struct node* right;
}Tree;

typedef struct 
{
	Tree *p;
	int count;
}Node;

//先序建立一个树,不存在的元素都用0代替
Tree* create_tree(void)
{
	Tree* root=NULL;
	char ch;

	cin>>ch;
	if(ch=='0')
		return NULL;
	else if(ch=='q')
		return root;
	else
	{
			root=(Tree*)malloc(sizeof(Tree));
			root->left=NULL;
			root->right=NULL;
			root->data=ch;
			root->left=create_tree();
			root->right=create_tree();
	}
	return root;
}

/*建立栈*/
#define MAX 100
typedef struct 
{
	Node data[MAX];
	int top;
}Stack;

Stack* create_stack(void)
{
	Stack* s=(Stack*)malloc(sizeof(Stack));
	if(s)
		s->top=-1;
	else
		cout<<"create stack error"<<endl;
	return s;
}

int empty_stack(Stack* s)
{
	if(s->top==-1)
		return 1;
	return 0;
}

int full_stack(Stack* s)
{
	if(s->top==MAX-1)
		return 1;
	return 0;
}

void push_stack(Stack* s,Node t)
{
	if(full_stack(s))
		return ;
	s->top++;
	s->data[s->top]=t;
}

void pop_stack(Stack* s,Node* t)
{
	if(empty_stack(s))
		return;
	*t=s->data[s->top];
	s->top=s->top-1;
}

int  get_stack(Stack* s,Node* t)
{
	if(empty_stack(s))
		return 0 ;
	*t=s->data[s->top];
	return 1;
}

void free_stack(Stack* s)
{
	free(s);
}


//后续遍历

void lastorder(Tree *t,char x)
{
	Tree* p=t;
	Node tempnode;
	Stack *s;
	
	s=create_stack();
	while(p!=NULL || !empty_stack(s))
	{
		if(p!=NULL)
		{
			tempnode.p=p;
			tempnode.count=0;
			push_stack(s,tempnode);
			p=p->left;
		}
		else //p==NULL
		{
			pop_stack(s,&tempnode);
			p=tempnode.p;
			if(tempnode.count==0)
			{
				tempnode.p=p;
				tempnode.count=1;
				push_stack(s,tempnode);
				p=p->right;
			}
			else
			{
				if(p->data==x)
				{
					cout<<p->data<<" ";
					Node ttmp;
					if(get_stack(s,&ttmp))
					{
						x=ttmp.p->data;
					}
				}
				p=NULL;
			}
		}
	}

	cout<<endl;
	free_stack(s);
}

//统计个数
int tree_count(Tree* t)
{
	if(t)
	{
		return 1+tree_count(t->left)+tree_count(t->right);
	}
	else
		return 0;
}

int main(void)
{
	Tree *root;
	root=create_tree();
    	
        /*
          以树上例子,输入先序树ab0d00ce00f00,打印节点d的祖先节点
        */

	lastorder(root,'d');
	return 0;
}

  

原文地址:https://www.cnblogs.com/buxianghe/p/3198662.html