一、题目描述(前序遍历)
二、思路
三者思路相似:递归!
重点!!前序遍历:中 --》左 --》右;中序遍历:左 --》中 --》右;后序遍历:左 --》右 --》中。
三、解题思路(前序遍历)
-
实现前序遍历递归接口函数
void preOrder(struct TreeNode* root, int* res, int* returnSize){
if(!root) return;
//前序遍历:中-》左-》右
res[(*returnSize)++] = root -> val;
preOrder(root -> left, res, returnSize);
preOrder(root -> right, res, returnSize);
}
-
让给定的二叉树进入递归
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int* res = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
preOrder(root, res, returnSize);
return res;
}
-
中序、后序遍历解题过程相似
四、代码
//前序遍历
void preOrder(struct TreeNode* root, int* res, int* returnSize){
if(!root) return;
//前序遍历:中-》左-》右
res[(*returnSize)++] = root -> val;
preOrder(root -> left, res, returnSize);
preOrder(root -> right, res, returnSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int* res = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
preOrder(root, res, returnSize);
return res;
}
//中序遍历
void inOrder(struct TreeNode* root, int* res, int* returnSize){
if(!root) return;
//中序遍历:左--》中--》右
inOrder(root -> left, res, returnSize);
res[(*returnSize)++] = root -> val;
inOrder(root -> right, res, returnSize);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
int* res = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
inOrder(root, res, returnSize);
return res;
}
//后序遍历
void postOrder(struct TreeNode* root, int* res, int* returnSize){
if(!root) return;
//后序遍历:左-》右-》中
postOrder(root -> left, res, returnSize);
postOrder(root -> right, res, returnSize);
res[(*returnSize)++] = root -> val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
int* res = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
postOrder(root, res, returnSize);
return res;
}
时间复杂度:O(n)。