问题:最长连续子序列是指:子节点的值大于父节点的值。
思路1:设置一个全局变量,记录树遍历时的最大连续长度,然后递归地求解树的长度,时间复杂度为O(n)
思路2:将每个结点作为根结点,依次求取每个结点的的最大连续子序列长度。时间复杂度为O(n^2)
相关程序实现:
思路1的相关程序实现:
#include <iostream>
#include<malloc.h>
using namespace std;
static int length=0;
typedef struct Btree
{
int num;
struct Btree *lchild;
struct Btree *rchild;
} *PBtree,Btree;
void inorder( PBtree root)
{
if(root==NULL)
return;
else
{
inorder(root->lchild);
cout<<root->num<<" ";
inorder(root->rchild);
}
}
//从根节点开始记录满足条件的长度
int getLong(PBtree root)
{
if(root==NULL)
return 0;
int res=-1;
if(root->lchild&&(root->lchild)->num>root->num)
res=max(res,getLong(root->lchild)+1);
if(root->rchild&&(root->rchild)->num>root->num)
res=max(res,getLong(root->rchild));
return res;
}
//在所有的路径中选择满足条件的最大长度
int getLongSubList(PBtree root)
{
if(root==NULL)
return 0;
int res=getLong(root);
if(root->lchild)
res=max(res,getLongSubList(root->lchild));
if(root->rchild)
res=max(res,getLongSubList(root->rchild));
return res+1;
}
int main()
{
PBtree root=NULL;
PBtree a1=new Btree();
PBtree a2=new Btree();
PBtree a3=new Btree();
PBtree a4=new Btree();
PBtree a5=new Btree();
PBtree a6=new Btree();
PBtree a7=new Btree();
PBtree a8=new Btree();
a1->num=10;
a2->num=1;
a3->num=2;
a4->num=3;
a5->num=4;
a6->num=6;
a7->num=1;
a8->num=2;
a1->lchild=a2;
a1->rchild=a3;
a2->lchild=a4;
a4->lchild=a5;
a5->lchild=a6;
a3->lchild=a7;
a7->lchild=a8;
inorder(a1);
cout<<endl;
cout<<getLongSubList(a1)<<endl;
return 0;
}
输出结果:
6 4 3 1 10 2 1 2
4
思路2的相关程序实现:
#include <iostream>
#include<malloc.h>
using namespace std;
static int length=0;
typedef struct Btree
{
int num;
struct Btree *lchild;
struct Btree *rchild;
} *PBtree,Btree;
void inorder( PBtree root)
{
if(root==NULL)
return;
else
{
inorder(root->lchild);
cout<<root->num<<" ";
inorder(root->rchild);
}
}
//从根节点开始记录满足条件的长度
int getLong(PBtree root)
{
if(root==NULL)
return 0;
if(root->lchild==NULL&&root->rchild==NULL)
{
length= max(length,1);
//cout<<length<<endl;
return 1;
}
int left_num=getLong(root->lchild);
int right_num=getLong(root->rchild);
if(root->lchild&&(root->lchild)->num>root->num)
left_num++;
if(root->rchild&&(root->rchild)->num>root->num)
right_num++;
if((root->lchild&&(root->lchild)->num<root->num)&&(root->rchild&&(root->rchild)->num<root->num))
{
length=max(length,1);
//cout<<length<<endl;
return 1;
}
length=max(length,max(left_num,right_num));
//cout<<length<<endl;
return max(left_num,right_num);
}
int main()
{
PBtree root=NULL;
PBtree a1=new Btree();
PBtree a2=new Btree();
PBtree a3=new Btree();
PBtree a4=new Btree();
PBtree a5=new Btree();
PBtree a6=new Btree();
PBtree a7=new Btree();
PBtree a8=new Btree();
a1->num=10;
a2->num=1;
a3->num=2;
a4->num=3;
a5->num=4;
a6->num=6;
a7->num=1;
a8->num=2;
a1->lchild=a2;
a1->rchild=a3;
a2->lchild=a4;
a4->lchild=a5;
a5->lchild=a6;
a3->lchild=a7;
a7->lchild=a8;
inorder(a1);
cout<<endl;
cout<<getLongSubList(a1)<<endl;
return 0;
}
输出结果:
6 4 3 1 10 2 1 2
4
总结:
树的遍历是自底向上的,每次都是先子树,在向上回溯。(先得到叶子节点的信息,然后逐次得到根的信息)