题解 | 实现二叉树先序,中序和后序遍历
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
#include<stdlib.h>
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
#include<stdlib.h>
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类 the root of binary tree
* @return int整型二维数组
* @return int* returnSize 返回数组行数
* @return int** returnColumnSizes 返回数组列数
*/
void num(struct TreeNode* root, int* number) {
if (root) {
(*number)++;
num(root->left, number);
num(root->right, number);
}
}
void xian(struct TreeNode* root, int* i, int* xi) {
if (root) {
xi[*i] = root->val;
(*i)++;
//printf("%d",root->val);
xian(root->left, i, xi);
xian(root->right, i, xi);
}
}
void zhong(struct TreeNode* root, int* z, int* zh) {
if (root) {
zhong(root->left, z, zh);
zh[*z] = root->val;
(*z)++;
//printf("%d",root->val);
zhong(root->right, z, zh);
}
}
void hou(struct TreeNode* root, int* h, int* ho) {
if (root) {
hou(root->left, h, ho);
hou(root->right, h, ho);
ho[*h] = root->val;
(*h)++;
//printf("%d",root->val);
}
}
int** threeOrders(struct TreeNode* root, int* returnSize,
int** returnColumnSizes ) {
// write code here
*returnSize = 3;
int number;
num(root, &number);
int** tree= (int**)malloc(*returnSize * sizeof(int*));
int* xi = (int*)malloc(number * sizeof(int));
int* zh = (int*)malloc(number * sizeof(int));
int* ho = (int*)malloc(number * sizeof(int));
*returnColumnSizes = (int*)malloc(*returnSize * sizeof(int));
for (int i = 0; i < *returnSize; i++) {
(*returnColumnSizes)[i] = number;
}
int x = 0;
int z = 0;
int h = 0;
xian(root, &x, xi);
zhong(root, &z, zh);
hou(root, &h, ho);
tree[0] = xi;
tree[1] = zh;
tree[2] = ho;
return tree;
}
二叉树的遍历直接使用递归就行,这道题主要是卡在于二维数组的表示上
查看16道真题和解析