链接:https://leetcode.cn/problems/binary-tree-preorder-traversal/solution/by-xun-ge-v-5hj0/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
解题思路
每次写递归,都按照这三要素来写,可以保证大家写出正确的递归算法:
具体实现
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);/右
中序
preorder(root->left, res, resSize);//左
res[(*resSize)++] = root->val;//根
preorder(root->right, res, resSize);/右
后序
preorder(root->left, res, resSize);//左
preorder(root->right, res, resSize);/右
res[(*resSize)++] = root->val;//根
单层递归的逻辑就是按照中左右的顺序来处理的,这样二叉树的前序遍历,基本就写完了
前序
- 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(root, res, returnSize);
- return res;
- }
中序
- void preorder(struct TreeNode* root, int* res, int* resSize) {
- if (root == NULL) {
- return;
- }
- preorder(root->left, res, resSize);
- res[(*resSize)++] = root->val;
- preorder(root->right, res, resSize);
- }
-
- int* preorderTraversal(struct TreeNode* root, int* returnSize) {
- int* res = malloc(sizeof(int) * 2000);
- *returnSize = 0;
- preorder(root, res, returnSize);
- return res;
- }
后序
- void preorder(struct TreeNode* root, int* res, int* resSize) {
- if (root == NULL) {
- return;
- }
- preorder(root->left, res, resSize);
- preorder(root->right, res, resSize);
- res[(*resSize)++] = root->val;
- }
-
- int* preorderTraversal(struct TreeNode* root, int* returnSize) {
- int* res = malloc(sizeof(int) * 2000);
- *returnSize = 0;
- preorder(root, res, returnSize);
- return res;
- }