题目
题目来源: LeetCode
前序遍历二叉树, 非递归实现
实现
//先实现栈, 利用栈实现非递归
int* _preorderTraversal(struct TreeNode* root, int* a){
Stack q;
StackInit(&q);
int index = 0;
//当栈不为空, root为空时
while(StackEmpty(&q) == 1 || root){
while(root){
StackPush(&q, root);
struct TreeNode* cur = StackTop(&q);
a[index++] = cur->val;
root = root->left;
}
struct TreeNode* cur = StackTop(&q);
root = cur->right;
StackPop(&q);
}
return a;
}
//获取二叉树的节点个数
int _returnSize(struct TreeNode* root){
if(!root){
return 0;
}
return _returnSize(root->left) + _returnSize(root->right) + 1;
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int* a = NULL;
*returnSize = _returnSize(root);
//开辟数组
a = (int*)malloc(sizeof(int) * (*returnSize));
if(!root){
return a;
}
a = _preorderTraversal(root, a);
return a;
}