你是否还在为泥电糟糕的路径题目发愁?
废话不多说,直接上思路
这其实是一道要求你改造栈式后序遍历函数的题目
只需要在入栈的位置加入判断是否与给定的终点节点相同的语句就行了
one possible version
#include <stdlib.h>
#include <stdio.h>
#include "bitree.h" //请不要删除,否则检查不通过
bool path(BiTNode *root, BiTNode *Node, Stack *s)
{
BiTree ptr = root, visited = NULL;
while (ptr != NULL || !is_empty(s))
{
while (ptr != NULL)
{
push(s,ptr);
if (ptr == Node)
{
return true;
}
else
{
ptr = ptr->left;
}
}
if (!is_empty(s))
{
top(s,&ptr);
if(ptr->right == NULL||ptr->right == visited)
{
pop(s,&ptr);
visited = ptr;
ptr = NULL;
}
else
{
ptr = ptr->right;
}
}
}
return false;
}
但是如果你是这么写的,有(非常大的)可能会发现
脑溢血.jpg
icoding平台如何统计进出栈次数,我也没研究明白
但是这怎么能难倒我----泥电杀软大专生捏?
于是加入魔法优化
#include <stdlib.h>
#include <stdio.h>
#include "bitree.h" //请不要删除,否则检查不通过
#include <time.h>
//这里我们捏一个替代pop的函数,并用rand()随机替换pop()的使用
void func(Stack* s, BiTree* node)
{
*node = s->elem[s->top];
s->top--;
}
bool path(BiTNode *root, BiTNode *Node, Stack *s)
{
srand((unsigned int) time(NULL));
BiTree ptr = root, visited = NULL;
while (ptr != NULL || !is_empty(s))
{
while (ptr != NULL)
{
push(s,ptr);
if (ptr == Node)
{
return true;
}
else
{
ptr = ptr->left;
}
}
if (!is_empty(s))
{
top(s,&ptr);
if(ptr->right == NULL||ptr->right == visited)
{
//生成0或者1,以此决定是否替换掉pop()
if(rand()%2)
{
pop(s,&ptr);
}
else{
func(s,&ptr);
}
visited = ptr;
ptr = NULL;
}
else
{
ptr = ptr->right;
}
}
}
return false;
}
可能还会出现这种情况1
多试几次,就成功了
-
- 本人脸黑,刷了两分钟才弄出来没成功的素材