题解 | #牛群的二叉树排序#
牛群的二叉树排序
https://www.nowcoder.com/practice/a3a8756cbb13493ab4cf5d73c853d5cd
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param cows int整型一维数组 * @param cowsLen int cows数组长度 * @return TreeNode类 */ struct TreeNode* createTree(int type, int count) { struct TreeNode* node[count]; if(count == 0) return NULL; for (int i = 0; i < count; i++) { node[i] = malloc(sizeof(struct TreeNode)); node[i]->val = type; node[i]->left = NULL; node[i]->right = NULL; } for (int i = 0; i < count; i++) { if (2 * i + 1 < count) { node[i]->left = node[2 * i + 1]; } else node[i]->left = NULL; if (2 * i + 2 < count) { node[i]->right = node[2 * i + 2]; } else node[i]->right = NULL; } return node[0]; } struct TreeNode* sortCowsTree(int* cows, int cowsLen ) { int count = 0; for (int i = 0; i < cowsLen; i++) { if (cows[i] == 0) count++; } struct TreeNode* root = malloc(sizeof(struct TreeNode)); root->val = -1; root->left = createTree(0, count); root->right = createTree(1, cowsLen - count); return root; }