题解 | #二叉树的前序遍历#
二叉树的前序遍历
http://www.nowcoder.com/practice/5e2135f4d2b14eb8a5b06fab4c938635
非递归方法,使用指针数组代替栈
int* preorderTraversal(struct TreeNode* root, int* returnSize ) {
int* res=(int*)malloc(sizeof(int)*100);
struct TreeNode* stack[100];
int head=0;
int tail=0;
struct TreeNode* node=root;
int k=0;
while(node||head!=tail){
if(node){
res[k++]=node->val;
stack[tail++]=node;
node=node->left;
}else{
node=stack[--tail];
node=node->right;
}
}
*returnSize=k;
return res;
}