二叉树三种顺序遍历应用
1.非递归,不允许用栈,求前序遍历最后一个结点
思想:前序遍历最后一个结点:若有右子树,则为右子树最右下结点,若有左子树,则为左子树最右下结点,否则为根结点。
#include "stdafx.h"
#include<iostream>
using namespace std;
typedef struct BTreeNode
{
int data;
struct BTreeNode *lchild,*rchild;
}BTree;
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
BTree *LastNode(BTree *b)
{
BTree *p=b;
if(p==NULL)return NULL;
else while(p)
{
if(p->rchild)p=p->rchild;
else if(p->lchild)p=p->lchild;
else return p;
}
}
2.满二叉树后序转化为前序递归
思想:对于满二叉树,根据任意一个遍历可将其转化为其他遍历
BTree PostToPre(int post[],int pre[],int l1,int h1,int l2,int h2)//后转前,l1,h1,l2,h2分别为序列初始后结束结点下标
{
if(h1>l1)
{
pre[h2]=post[h1];//根结点
int half=(h1-l1)/2;//左子树或右子树的结点数
PostToPre(post,pre,l1,l1+half-1,l2+1,l2+half);//左子树后序转前序
PostToPre(post,pre,l1+half,h1-1,l2+half+1,h2);//右子树后序转前序
}
}
浙公网安备 33010602011771号