题目详见:LeetCode二叉树前序遍历
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void preorder(struct TreeNode* root,int* res,int* resSize){
if(root==NULL){
return;
}
res[(*resSize)++]=root->val;
preorder(root->left,res,resSize);
preorder(root->right,res,resSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int* res = malloc(sizeof(int)*2000); //定义一个数组,树结点按照遍历顺序存在该数组中,以便打印遍历结果
*returnSize = 0; //用来传到preorder函数中,对res下标进行移位
preorder(root,res,returnSize);
return res;
}
迭代
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int* res = malloc(sizeof(int)*2000); //res指向这块内存的起始地址
*returnSize = 0;
if(root == NULL){
return res;
}
struct TreeNode* stk[20000]; //这个栈用来存遍历过的结点,方便找到当前结点的父结点,实际上,栈顶元素就是当前结点的父结点
struct TreeNode* node = root;
int stk_top=0; //此处用数组来代替栈,因为需要一个变量记录栈顶元素的位置
while(stk_top>0||node != NULL){
while(node!=NULL){
res[(*returnSize)++] = node->val;
stk[stk_top++] = node;
node = node->left;
}
node = stk[--stk_top];
node = node->right;
}
return res;
}