1.题目:
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
2.代码:
/**
* 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* Tree;
typedef struct{
Tree* array;
int top;
}Stack;
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize=0;
int *r=malloc(1000*sizeof(int));
Stack* s=(Stack *)malloc(sizeof(Stack));
s->array=(Tree *)malloc(1000*sizeof(Tree));
s->top=0;
while(root||s->top){ //root保证刚开始s->top==0时能进while
if(root){
r[(*returnSize)++]=root->val; //visit()
s->array[s->top++]=root; //push()
root=root->left; //->left
}
else{
root=s->array[--s->top]; //pop()
root=root->right; //->right
}
}
return r;
}
3.知识点:
二叉树前序非递归。