递归
#define MAX_NUM 100
int *result = NULL;
void myPreOrder(struct TreeNode *root, int *returnSize)
{
if (root == NULL) return;
result[(*returnSize)++] = root->val; // 根
myPreOrder(root->left, returnSize); // 左
myPreOrder(root->right, returnSize); // 右
return;
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize = 0;
if (NULL == root) return NULL;
result = (int *)malloc(sizeof (int) * MAX_NUM);
myPreOrder(root, returnSize);
return result;
}
迭代:
还是利用栈, 但是加入栈的时候, 是先root, 再right, 而不是left。
#define MAX_NUM 100
int *preorderTraversal(struct TreeNode *root, int *returnSize) {
*returnSize = 0;
if (NULL == root) return NULL;
int *result = (int *)malloc(sizeof(int) * MAX_NUM);
struct TreeNode *stack[MAX_NUM] = {0};
int top = -1;
int i = 0;
struct TreeNode *tmp = root;
while (tmp || top >= 0) {
if (tmp) {
stack[++top] = tmp;
}
// 从栈中取出栈顶元素, 放入待返回的数组中
tmp = stack[top--];
result[i++] = tmp->val;
//把右孩子加入栈中
if (tmp->right) {
stack[++top] = tmp->right;
}
tmp = tmp->left;
}
*returnSize = i;
return result;
}