144.二叉树的前序遍历

题目来源:力扣icon-default.png?t=M85Bhttps://leetcode.cn/problems/binary-tree-preorder-traversal/题目简介:

给定二叉树的根节点root,返回它的前序遍历

思路:

递归

代码实现:

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;
}

你可能感兴趣的:(leetcode专栏,leetcode,算法,职场和发展)