二叉树的先序遍历

给定一个二叉树,返回它的 前序 遍历。

示例:

输入: [1,null,2,3]  
  1
   \
    2
   /
  3 

输出: [1,2,3]

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/
递归实现访问
二叉树的先序遍历_第1张图片
递归实现

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
//计算节点的个数
int TreeNodeSize(struct TreeNode *root)
{
    if(NULL == root)
        return 0;
    return 1 + TreeNodeSize(root->left) + TreeNodeSize(root->right);
}
//把节点信息写入数组
void _preorderTraversal(struct TreeNode *root,int *array,int *pIndex)
{
    if(NULL == root)
        return;
    array[*pIndex]=root->val;
    (*pIndex)++;
    _preorderTraversal(root->left,array,pIndex);
    _preorderTraversal(root->right,array,pIndex);
}

int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    *returnSize=TreeNodeSize(root);
    int *array=(int *)malloc(*returnSize * sizeof(int));
    int *index=0;
    //数组下标要用地址传递
    _preorderTraversal(root,array,&index);
    return array;
}

你可能感兴趣的:(二叉树的先序遍历)