给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
输出: [1,2,3]
解题思路
1,因为题中要求返回一个存放二叉树的前序遍历的数组,所以需要知道树中有多少个结点,申请多大的数组来存放数据。
2,前序遍历是将二叉树用N(根节点)L(左孩子)R(右孩子)的方式进行遍历。
/**
* 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().
*/
typedef struct TreeNode Node;
int CountNode(Node* root)//利用递归 每次返回当前结点的左子树和右子树的节点数加一。
{
if(NULL == root)
return 0;
else
return CountNode(root->left)+CountNode(root->right)+1;
}
void preorder(Node* root,int* index,int* ret)// index 当做数组的下标 ret是数组名称
{
if(NULL == root)
return;
else
{
ret[(*index)++] = root->val;
preorder(root->left,index,ret);
preorder(root->right,index,ret);
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize)
{
if(NULL == root)
return NULL;
int count = CountNode(root);
int* ret = (int*)malloc(sizeof(int)*count);
*returnSize = 0;
preorder(root,returnSize,ret);
return ret;
}