LeetCode | 二叉树的前中后序遍历
void preorder(struct TreeNode* root,int* a,int* pi)
{
if(root == NULL)
return;
a[(*pi)++] = root->val;
preorder(root->left,a,pi);
preorder(root->right,a,pi);
}
int TreeSize(struct TreeNode* root)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
//计算树有多少个节点
int n = TreeSize(root);
*returnSize = n;
//开辟n个大小
int* a = malloc(sizeof(int) * n);
int i = 0;
//前序遍历
preorder(root,a,&i);
return a;
}
int TreeSize(struct TreeNode* root)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
void inorder(struct TreeNode* root,int* a ,int* pi)
{
if(root == NULL)
return;
inorder(root->left,a,pi);
a[(*pi)++] = root->val;
inorder(root->right,a,pi);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int n = TreeSize(root);
int* a = (int*)malloc(sizeof(int) * n);
*returnSize = n;
int i = 0;
inorder(root,a,&i);
return a;
}
int TreeSize(struct TreeNode* root)
{
return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}
void postorder(struct TreeNode* root,int* a ,int* pi)
{
if(root == NULL)
return;
postorder(root->left,a,pi);
postorder(root->right,a,pi);
a[(*pi)++] = root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
int n = TreeSize(root);
int* a = (int*)malloc(sizeof(int) * n);
*returnSize = n;
int i = 0;
postorder(root,a,&i);
return a;
}
原文地址:https://blog.csdn.net/2201_76004325/article/details/134767712
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_38960.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。