144. 二叉树的前序遍历
给定一个二叉树,返回它的 前序 遍历。
输入: [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;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
void Ptree(struct TreeNode* root,int *res,int *count)
{
if(root == NULL) return;
res[(*count)++] = root->val;
Ptree(root->left,res,count);
Ptree(root->right,res,count);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
if(root == NULL) return NULL;
*returnSize = 0; //记录当前位置
int *res = (int *)malloc(sizeof(int)*1000);
Ptree(root,res,returnSize);
return res;
}
94. 二叉树的中序遍历
给定一个二叉树,返回它的中序 遍历
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
递归实现:
/**
* 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().
*/
void Ptree(struct TreeNode* root,int* res,int* count)
{
if(root == NULL) return;
Ptree(root->left,res,count);
res[(*count)++] = root->val;
Ptree(root->right,res,count);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
if(root == NULL) return NULL;
*returnSize = 0;
int* res = (int*)malloc(sizeof(int)*1000);
Ptree(root,res,returnSize);
return res;
}
145. 二叉树的后序遍历
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,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().
*/
void Ptree(struct TreeNode* root,int* res,int* count)
{
if(root == NULL) return;
Ptree(root->left,res,count);
Ptree(root->right,res,count);
res[(*count)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
if(root == NULL) return NULL;
*returnSize = 0;
int* res = (int*)malloc(sizeof(int)*1000);
Ptree(root,res,returnSize);
return res;
}