#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;
}
后序遍历非递归求结点的所有祖先(或求两个节点的最近公共祖先)
最新推荐文章于 2023-11-23 13:06:11 发布