对于二叉树,广度优先搜索遍历(BFS)是否与预序遍历相同?我对这两种不同类型的遍历有点困惑。任何人都可以向我解释一下吗?此外,预序遍历与深度优先搜索遍历(DFS) 相比如何?
非常感谢!
结构问题.
我写了一个实现堆栈的代码.如果我将sqStack*sq传递给此函数init_stack(),则代码最终会出错.如以下代码的注释中所示.
但后来我发现如果我将sqStack&sq传递给init_stack()函数,代码就可以了.
有谁可以向我解释一下?谢谢!
#include <stdio.h>
#include <stdlib.h>
#define init_size 10
#define increment 1
typedef struct sqStack
{
int* top;
int* base;
int stack_size;
}sqStack;
int init_stack(sqStack* sq)
{
if(sq->base==NULL)
{
sq->base = (int*)malloc(init_size*sizeof(int));
}
if(sq->base==NULL) exit(-1);
sq->stack_size=init_size;
sq->top=NULL;
sq->top=sq->base;
return 1;
}
int push(sqStack* sq, int e)
{
if(sq==NULL) exit(-1);
if(sq->top-sq->base==sq->stack_size)
{
int* q = (int*)realloc(sq->base,
(init_size+increment)*sizeof(int));
if(q==NULL) exit(-1);
sq->base=q;
sq->stack_size += increment;
sq->top=sq->base+sq->stack_size;
}
*sq->top++=e;//Thread 1: EXC_BAD_ACCESS If I pass sqStack* sq to this function, error occurs. But …Run Code Online (Sandbox Code Playgroud) 我尝试使用递归创建二叉树,但是当我键入时ABD***CE**FG***,代码未产生任何结果。我按了空格键,但是代码仍然没有成功。代码是错误的还是我的输入错误?
#include <stdio.h>
#include <stdlib.h>
typedef struct tree
{
struct tree *left;
struct tree *right;
char val;
}treeNode;
void createTree(treeNode **node)
{
char value=0;
value=getchar();
if(value=='*')
*node=NULL;
else
{
*node = (treeNode*)malloc(sizeof(treeNode));
if(!*node) exit(-1);
(*node)->val=value;
createTree(&(*node)->left);
createTree(&(*node)->right);
}
}
void preOrder(treeNode *node)
{
if (node==NULL) return;
putchar(node->val);
preOrder(node->left);
preOrder(node->right);
}
int main() {
// insert code here...
treeNode **node;
createTree(node);
preOrder(*node);
return 0;
}
Run Code Online (Sandbox Code Playgroud) 如果我为指针动态分配了空间,请列出以下内容:
int *a = (int*)malloc(sizeof(int));
Run Code Online (Sandbox Code Playgroud)
代码完成后,我应该释放一个吗?谢谢!