144. 二叉树的前序遍历 - 力扣(LeetCode)
给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
这道题的启发性真的很强 ,这里必须传入i的指针进去,下一次栈帧i++,但回到了上一层i又变回到了原来的i,所以这里需要用指针来控制数组的下表
/*** 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().*/
int TreeSize(struct TreeNode* root)
{if(root==NULL){return 0;}return TreeSize(root->left)+TreeSize(root->right)+1;
}
void preorder(struct TreeNode* root,int* arr, int* pi)
{if(root==NULL){return;}arr[(*pi)++]=root->val;preorder(root->left,arr,pi);preorder(root->right,arr,pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {*returnSize=TreeSize(root);int* arr=(int*)malloc(sizeof(int)*(*returnSize));int i=0;preorder(root,arr,&i);return arr;
}