二叉树遍历
前序遍历:
代码:
/**
* 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().
*/
typedef struct TreeNode TreeNode;
// ⼆叉树结点个数
int BinaryTreeSize(TreeNode* root)
{
if (root == NULL)
{
return 0;
}
return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}
//表示是当前函数的子函数
void _preorderTraversal(TreeNode* root,int* arr,int* pi){
if (root == NULL)
{
return;
}
//根左右
arr[(*pi)++] = root->val;
_preorderTraversal(root->left,arr,pi);
_preorderTraversal(root->right,arr,pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
//int* returnSize是一个整型数组
//1.先求出二叉树结点的个数
*returnSize = BinaryTreeSize(root);
//2.动态申请内容---arr的大小
int* returnArr = (int*)malloc(sizeof(int)*(*returnSize));
//开始前序遍历
int i = 0;
_preorderTraversal(root,returnArr,&i);
return returnArr;
}
中序遍历:
代码:
/**
* 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().
*/
typedef struct TreeNode TreeNode;
// ⼆叉树结点个数
int BinaryTreeSize(TreeNode* root)
{
if (root == NULL)
{
return 0;
}
return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}
//表示是当前函数的子函数
void _preorderTraversal(TreeNode* root,int* arr,int* pi){
if (root == NULL)
{
return;
}
//左根右
_preorderTraversal(root->left,arr,pi);
arr[(*pi)++] = root->val;
_preorderTraversal(root->right,arr,pi);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
//int* returnSize是一个整型数组
//1.先求出二叉树结点的个数
*returnSize = BinaryTreeSize(root);
//2.动态申请内容---arr的大小
int* returnArr = (int*)malloc(sizeof(int)*(*returnSize));
//开始中序遍历
int i = 0;
_preorderTraversal(root,returnArr,&i);
return returnArr;
}
后序遍历:
代码:
/**
* 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().
*/
typedef struct TreeNode TreeNode;
// ⼆叉树结点个数
int BinaryTreeSize(TreeNode* root)
{
if (root == NULL)
{
return 0;
}
return 1 + BinaryTreeSize(root->left) + BinaryTreeSize(root->right);
}
//表示是当前函数的子函数
void _preorderTraversal(TreeNode* root,int* arr,int* pi){
if (root == NULL)
{
return;
}
//左右根
_preorderTraversal(root->left,arr,pi);
_preorderTraversal(root->right,arr,pi);
arr[(*pi)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
//int* returnSize是一个整型数组
//1.先求出二叉树结点的个数
*returnSize = BinaryTreeSize(root);
//2.动态申请内容---arr的大小
int* returnArr = (int*)malloc(sizeof(int)*(*returnSize));
//开始后序遍历
int i = 0;
_preorderTraversal(root,returnArr,&i);
return returnArr;
}