longest increasing in binary tree
longest consective increasing sequence in binary tree.(start point happen anywhere in the node, not necessary start from root)
没有OJ,继续不知道这样做对不对 分情况讨论
- 左结点,右节点都要返回其递增数目和递减数目
- root节点需要根据左右节点实际值判断是否用递增递减数目
- 考虑到NULL的情况
int getLongest(TreeNode *root)
{
int up=0,down=0;
get(root,up,down);
return maxNum;
}
int maxNum=0;
void get(TreeNode *root,int &up,int &down)
{
if(root==0)
{
up=0,down=0;
}
int lup=0,ldown=0;
int rup=0,rdown=0;
if(root->left)
get(root->left,lup,ldown);
if(root->right)
get(root->right,rup,rdown);
if(root->left==NULL)
{
if(root->right==NULL)return ;
if(root->right->val<root->val)down=rdown+1;
if(root->right->val>root->val)up=rup+1;
maxNum=max(maxNum,max(down,up));
}
else if(root->right==NULL)
{
if(root->left->val<root->val)down=ldown+1;
if(root->left->val>root->val)up=lup+1;
maxNum=max(maxNum,max(down,up));
}
else
{
if(root->left->val > root->val && root->val>root->right->val)
{
maxNum=max(maxNum,lup+1+rdown);
}
else if(root->left->val<root->val && root->val<root->right->val)
{
maxNum=max(maxNum,ldown+1+rup);
}
if(root->left->val<root->val)
down=max(down,ldown+1);
if(root->left->val>root->val)
up=max(up,lup+1);
if(root->right->val<root->val)
down=max(down,rdown+1);
if(root->right->val>root->val)
up=max(up,rup+1);
}
}