劍值offer66題之每日一題——第四題
阿新 • • 發佈:2018-11-12
題目描述:
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回
思路:運用遞迴的思想,每一棵子樹的構建方式都一樣,先遞迴的構建左右子樹,最後生成大樹返回根節點
程式碼實現:
class Solution { public: TreeNode* reConstruct(vector<int> pre,//原始先序數列 int startPre,//當前子樹先序在原始先序數列中的起始位置 int endPre,//當前子樹先序在原始先序數列中的結束位置 vector<int> vin,//原始中序數列 int startVin,//當前子樹中序在原始中序數列中的起始位置 int endVin )//當前子樹中序在原始中序數列中的結束位置 { if(startPre>endPre||startVin>endVin) return NULL; TreeNode* root=new TreeNode(pre[startPre]);//當前先序的第一個數為當前子樹的根節點 for(int i=startVin;i<=endVin;i++)//在當前子樹的中序數列中找到根節點下標位置i { if(vin[i]==pre[startPre]) { //先構建當前子樹的左子樹 root->left=reConstruct(pre,startPre+1,startPre+i-startVin,vin,startVin,i-1); //在構建當前子樹的右子樹 root->right=reConstruct(pre,startPre+i-startVin+1,endPre,vin,i+1,endVin); break; } } //當前樹的左右子樹構建完成,返回這棵樹 return root; } TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int Prelength=pre.size();//先序長度 int Vinlength=vin.size();//中序長度 return reConstruct(pre,0,Prelength-1,vin,0,Vinlength-1); } };