劍指offer(四):重建二叉樹
阿新 • • 發佈:2020-08-18
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。 剛開始的思路:class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if(pre.size()>0&&vin.size()>0){return reConstructBinaryTree2(pre,vin,0,pre.size()-1,0,vin.size()-1); } return NULL; } TreeNode* reConstructBinaryTree2(vector<int> pre,vector<int> vin, int preStart,int preEnd, int vinStart,intvinEnd){ if(preStart>preEnd || vinStart>vinEnd ) return NULL; TreeNode* root = new TreeNode(pre[preStart]); vector<int>::iterator it = find(vin.begin(),vin.end(),pre[preStart]); int mid = &*it-&vin[0]; int len = mid - vinStart; root->left = reConstructBinaryTree2(pre,vin,preStart+1,preStart+len,vinStart,mid-1); root->right = reConstructBinaryTree2(pre,vin,preStart+len+1,preEnd,mid+1,vinEnd); return root; } };
記得中間變數要寫在裡面,不能寫在遞迴函式外面
檢視劍指offer之後修改了遞迴條件
class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if(pre.size()>0&&vin.size()>0){ return reConstructBinaryTree2(pre,vin,0,pre.size()-1,0,vin.size()-1); } return NULL; } TreeNode* reConstructBinaryTree2(vector<int> pre,vector<int> vin, int preStart,int preEnd, int vinStart,int vinEnd){ TreeNode* root = new TreeNode(pre[preStart]); if(preStart == preEnd && vinStart == vinEnd && pre[preStart]==vin[vinStart]){ return root; } vector<int>::iterator it = find(vin.begin(),vin.end(),pre[preStart]); int mid = &*it-&vin[0]; int len = mid - vinStart; if(len>0) root->left = reConstructBinaryTree2(pre,vin,preStart+1,preStart+len,vinStart,mid-1); if(len<preEnd - preStart) root->right = reConstructBinaryTree2(pre,vin,preStart+len+1,preEnd,mid+1,vinEnd); return root; } };