題目:輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如:輸入前序遍歷和中序遍歷,請重建該二叉樹。
#include #include #include using namespace std;
typedef struct treenode
treenode, *tree;
tree constructtree(int* startpreorder, int* endpreorder, int* startinorder, int* endinorder)
int* rootinoder = startinorder;
while (rootinoder <= endinorder && *rootinoder != rootval)
rootinoder++;
if (rootinoder == endinorder && *rootinoder != rootval)
throw std::exception("input invaild");
int leftlength = rootinoder - startinorder;
int* leftendproorder = startpreorder + leftlength;
if (leftlength > 0)
if (leftlength < endpreorder - startpreorder)
return root;
}int main()
; int inorder[8] = ;
tree root = constructtree(preorder, preorder + 7, inorder, inorder + 7);
}
面試題7 重建二叉樹
對vector使用指標 include include include using namespace std int main vector seq 3 vector curr 0 for int j 0 j 3 j getchar struct treenode struct listnode ...
面試題7 重建二叉樹
一 題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建出圖2.6所示的二叉樹並輸出它的頭結點。二 關鍵 根據前序找根節點,從而在中序中找到左子樹對應的序列,右子樹對應的序列。三 解釋 四 i...
面試題7 重建二叉樹
面試題7 重建二叉樹 題目 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸 入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建出 圖所示的二叉樹並輸出它的頭結點。假裝有圖.jpg 1 2 3 4 5 6 7 8 在preorder inord...