题解 | #重建二叉树#
重建二叉树
https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param preOrder int整型一维数组 * @param preOrderLen int preOrder数组长度 * @param vinOrder int整型一维数组 * @param vinOrderLen int vinOrder数组长度 * @return TreeNode类 */ struct TreeNode* maketree(int pl , int pr , int* preOrder , int vl , int vr , int* vinOrder){ if(pl > pr || pr < 0 || vl > vr || vr < 0) return NULL; struct TreeNode* root = (struct TreeNode*)malloc(sizeof(struct TreeNode)); root->val = preOrder[pl]; int i = vl; while(i <= vr){ if(vinOrder[i] == preOrder[pl]) break; i++; } root->left = maketree(pl + 1 , pl + i - vl , preOrder , vl , i - 1 , vinOrder); root->right = maketree(pl + i - vl + 1 , pr , preOrder , i + 1 , vr , vinOrder); return root; } struct TreeNode* reConstructBinaryTree(int* preOrder, int preOrderLen, int* vinOrder, int vinOrderLen ) { // write code here int pl = 0 , pr = preOrderLen - 1; int vl = 0 , vr = vinOrderLen - 1; struct TreeNode* root = maketree(pl , pr , preOrder , vl , vr , vinOrder); return root; }