题解 | 重建二叉树
/** * 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* reConstructBinaryTree(int* preOrder, int preOrderLen, int* vinOrder, int vinOrderLen ) { int iroot = 0; int ileft = 0; int iright = 0; struct TreeNode* pTreeNode = NULL; if(0 == preOrderLen)return NULL; pTreeNode = (struct TreeNode*)malloc(sizeof(struct TreeNode)); memset(pTreeNode,0x00,sizeof(struct TreeNode)); iroot = preOrder[0]; for (int i = 0; i < preOrderLen; i++){ if(iroot == vinOrder[i])break; ileft++; } iright = vinOrderLen - ileft - 1; pTreeNode->val = iroot; pTreeNode->left = reConstructBinaryTree(&preOrder[1],ileft,&vinOrder[0],ileft); pTreeNode->right = reConstructBinaryTree(&preOrder[1+ileft],iright,&vinOrder[1+ileft],iright); return pTreeNode; }
先通过前序遍历找到根节点,再将根节点代入中序遍历得到左子树数量,再反代入前序遍历得到左子树进而得到右子树,再将其带入到reConstructBinaryTree 函数得到重建的二叉数,作为小白我不知道有这个函数,想了好久hhh