oj面试题
1、非递归实现二叉树的前序遍历
/**
- Definition for a binary tree node.
- struct TreeNode {
-
int val;
-
struct TreeNode *left;
-
struct TreeNode *right;
- };
/
/* - Return an array of size *returnSize.
- Note: The returned array must be malloced, assume caller calls free().
*/
typedef struct TreeNode* STDataType;
typedef struct Stack
{
STDataType* _array;
int _top;//栈顶
int _capacity;//容量
}Stack;
void StackInit(Stack* ps);
void StackDestory(Stack* ps);
void StackPush(Stack* ps,STDataType x);
void StackPop(Stack* ps);
STDataType StackTop(Stack* ps);
int StackEmpty(Stack* ps);
int StackSize(Stack* ps);
void StackInit(Stack* ps)
{
assert(ps);
ps->_array = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
void StackDestory(Stack* ps)
{
assert(ps);
free(ps->_array);
ps->_array = NULL;
ps->_capacity = 0;
ps->_top = 0;
}
void StackPush(Stack* ps, STDataType x)
{
assert(ps);
if (ps->_top == ps->_capacity)
{
size_t newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
ps->_array = (STDataType*)realloc(ps->_array, sizeof(STDataType)*newcapacity);
assert(ps->_array != NULL);
ps->_capacity = newcapacity;
}
//ps->_top = x;
ps->_array[ps->_top]=x;
ps->_top++;
}
void StackPop(Stack* ps)
{
assert(ps && ps->_top > 0);
ps->_top--;
}
STDataType StackTop(Stack* ps)
{
assert(ps);
return ps->_array[ps->_top-1];//
}
int StackEmpty(Stack* ps)
{
assert(ps);
return ps->_top == 0 ? 0 : 1;
}
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{
Stack s;
StackInit(&s);
struct TreeNode* cur=root;
while(StackEmpty(&s)!=0 || cur!=NULL)
{
//访问左路节点并入栈
while(cur!=NULL)
{
printf("%d ",cur->val);
++(returnSize);//计算出总节点个数
StackPush(&s,cur);
cur=cur->left;
}
struct TreeNode top=StackTop(&s);
StackPop(&s);
//左路节点的右子树入栈
cur=top->right;
}
int* prearray=(int*)malloc(4*(returnSize));
int i=0;
cur=root;
while(StackEmpty(&s)!=0 || cur!=NULL)
{
//访问左路节点并入栈
while(cur!=NULL)
{
printf("%d ",cur->val);
prearray[i]=cur->val;
i++;
StackPush(&s,cur);
cur=cur->left;
}
struct TreeNode top=StackTop(&s);
StackPop(&s);
//左路节点的右子树入栈
cur=top->right;
}
return prearray;
}