已知前序中序,重建二叉樹(加7種遍歷的方式)

2021-08-14 12:47:40 字數 2572 閱讀 5401

//在中序遍歷中找到根節點的值

int * rootinorder = begininorder;

while (rootinorder <= endinorder && *rootinorder != rootvalue) ++rootinorder;

if (rootinorder == endinorder && *rootinorder != rootvalue)

throw std::exception("invalid input . ");

int leftlength = rootinorder - begininorder; //左子樹的長

int * leftpreorderend = beginpreoder + leftlength; //前序陣列中 左子樹的末尾

if (leftlength > 0) //左子樹不為空,建立左子樹

if (leftlength < endpreorder - beginpreoder) //建立右子樹

return root;

}//通過前序遍歷和中序遍歷來重建二叉樹

binarytreenode* construct(int * preorder, int * inorder, int length)

//二叉樹遞迴前序遍歷

void preordervisit(binarytreenode * t)

}//二叉樹遞迴中序遍歷

void inordervisit(binarytreenode * t)

}//二叉樹遞迴後序遍歷

void lastordervisit(binarytreenode * t)

}//層序二叉樹遍歷

void levelordervisit(binarytreenode *t)

}//非遞迴前序遍歷

void noprerecursivevist(binarytreenode *t)

else

}}//非遞迴中序遍歷

void noinrecursivevist(binarytreenode * t)

else

}}//非遞迴後序遍歷

void nolastrecursivevist(binarytreenode * t)

p = s.top();

if (p->m_pright == null || p->m_pright == pre) //如果沒有右兒子,或者右子樹全部訪問完畢,則輸出此根節點

else

p = p->m_pright; }}

int main()

; int inorder[8] = ;

binarytreenode * node = construct(preorder, inorder,8);

cout << "先序遍歷" << endl;

preordervisit(node);

cout << endl;

cout << "非遞迴先序遍歷二叉樹" << endl;

noprerecursivevist(node);

cout << endl;

cout << "中序遍歷" << endl;

inordervisit(node);

cout << endl;

cout << "非遞迴中序遍歷二叉樹" << endl;

noinrecursivevist(node);

cout << endl;

cout << "後序遍歷" << endl;

lastordervisit(node);

cout << endl;

cout << "非遞迴後序遍歷二叉樹" << endl;

nolastrecursivevist(node);

cout << endl;

cout << "層序遍歷" << endl;

levelordervisit(node);

cout << endl;

system("pause");

return 0;

}

已知前序和中序遍歷,重建二叉樹

想在牛客網上寫此題目,此處 題目描述 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。分析 前序遍歷 根節點 左子樹 右子樹 中序遍歷 左子樹 根節點 右子樹 後序遍歷 左子樹 右...

已知二叉樹的前序和中序,重建二叉樹 筆記

題目如下 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。分析 二叉樹的前序遍歷順序是 先訪問根節點,然後前序遍歷左子樹,再前序遍歷右子樹。中序遍歷順序是 中序遍歷根節點的左子樹,...

已知前序 中序 求二叉樹

題目如下 輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。分析 二叉樹的前序遍歷順序是 先訪問根節點,然後前序遍歷左子樹,再前序遍歷右子樹。中序遍歷順序是 中序遍歷根節點的左子樹,...