后序遍历非递归求结点的所有祖先(或求两个节点的最近公共祖先)

#include "stdafx.h"
#include<cstdio>
#include<iostream>
#include<vector>
#include<stack>

using namespace std;
const int maxn=100;
struct node{
	int data;
	int tag;
	node*l,*r;};

	void postorder(node *root){//后序遍历的非递归写法
		node* p=root,*r=NULL;
		stack<node*>s;

		while(p||!s.empty()){
			if(p){
				s.push(p);
				p=p->l;

			}
			else{
				p=s.top();
				if(p->r&&p->r!=r){
					p=p->r;
				}
				else {s.pop();
				r=p;
				p=NULL;
				}
			}
		}
	}


	void search(node *root,int x){//求data为x的节点的所有祖先
		node* p=root;
		stack<node*>s;
		while(p||!s.empty()){
			while(p&&p->data!=x){
				s.push(p);
				p->tag=0;
				p=p->l;

			}
			if(p->data==x){
				while(!s.empty()){
					cout<<s.top()<<" ";
					s.pop();
				}
			}
			while(!s.empty()&&s.top()->tag==1){s.pop();}
			if(!s.empty()){s.top()->tag=1;p=s.top()->r;}
		}
	}


	node* ancestor(node *root,node *p,node *q){//求节点p和q的最近公共祖先,假设p在q的左边
		node* bt=root;
		stack<node*>s,s1;
		while(bt||!s.empty()){
			while(bt&&bt!=p&&bt!=q)
				while(bt){
					s.push(bt);
					bt->tag=0;
					bt=bt->l;}
				while(!s.empty()&&s.top()->tag==1){
					if(s.top()==p){
						s1=s;


					}
					if(s.top()==q){
                                         //遍历s1和s比较找到最近公共祖先即可

					}
					s.pop();

				}

				if(!s.empty()){s.top()->tag=1;
				bt=s.top()->r;}}

		return NULL


	}







	int main(){

		
		return 0;
	}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值