LeetCode探索: 二叉树的前序遍历[C语言]
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
// #define MAX 10000
// int res[MAX] = {0};
// 递归计算节点个数
int CountNode(struct TreeNode* root) {
if(root==NULL) return 0;
return CountNode(root->left) + CountNode(root->right) + 1;
}
void preorder(struct TreeNode* root, int* res, int* returnSize){
if(root==NULL) return;
res[(*returnSize)] = root->val;
(*returnSize)++;
preorder(root->left, res, returnSize);
preorder(root->right, res, returnSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize = 0;
if(root==NULL) return NULL;
// 计算有多少个节点
int cnt = CountNode(root);
// printf("%d",cnt);
int bufSize = sizeof(int)*cnt;
int* res = (int*)malloc(bufSize);
memset(res, 0, bufSize);
// *returnSize = 0;
// preorderTraversal(root)
preorder(root, res, returnSize);
return res;
}