根據二叉樹的前序遍歷和中序遍歷結果重建出該二叉樹

2021-06-21 09:25:54 字數 1417 閱讀 3867

struct binarytreenode{

int m_nvalue;

binarytreenode* m_nleft;

binarytreenode* m_nright;

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

if(preorder=null||inorder=null||length<=0)

return null;

return constructcore(preorder,preorder+length-1,inorder,inorder+length-1);

binarytreenode* constructcore(int* startpreorder,int* endpreorder,int* startinorder,int* endinorder){

int rootvalue=startpreorder[0]; //第乙個值為根節點

binarytreenode* root=new binarytreenode();

root->m_nvalue=rootvalue;

root->m_nleft=root->m_nright=null; //構建節點

if(startpreorder=endpreorder){

if(startinorder=endinorder&&*startpreorder=*startinorder) //只有乙個結點的時候

return root;

else

throw exception("invalid input");

int* rootinorder=startinorder;

while(rootinorder<=endinorder&&*rootinorder!=rootvalue) //在中序遍歷中找到根節點

++rootinorder;

if(rootinorder==endinorder&&*rootinorder!=rootvalue) //找到最後一點也不是要找的值則輸入有誤

throw exception("invalid input");

int leftlength=rootinorder-startinorder;

int* leftpreorderend=startpreorder+leftlength;

if(leftlength>0){

root->m_nleft=constructcore(startpreorder+1,leftpreorderend,startinorder,rootinorder-1);

if(leftlenthroot->m_nright=constructcore(leftpreorderend+1,endpreorder,rootinorder+1,endinorder);

根據前序遍歷和中序遍歷重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列和中序遍歷序列,則重建二叉樹並返回。class treenode public class s2 public treenode reconstruct int pre...

根據前序遍歷和中序遍歷重建二叉樹

package com.study 根據二叉樹的前序遍歷和中序遍歷結果重建二叉樹 並輸出其頭節點。假設前序遍歷和中序遍歷結果中沒有重複數字 前序遍歷序列 中序遍歷序列 class treenode public class suanfa4 private static int arr2 public...

根據前序遍歷和中序遍歷樹構造二叉樹

根據前序遍歷和中序遍歷樹構造二叉樹.樣例給出中序遍歷 1,2,3 和前序遍歷 2,1,3 返回如下的樹 2 1 3 假設樹中不存在相同數值的節點 definition of treenode class treenode class solution treenode helper vector p...