标签:logs new ptr 剑指offer 构建 efi binary nod 长度
思路还是很明了的,不知道为啥就是过不去了。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { int rootval = pre[0]; TreeNode* root = new TreeNode(rootval); return helper(root, pre, vin); } TreeNode* helper (TreeNode *preroot,vector<int> pre,vector<int> vin) { int lenL = 0,lenR = 0,i = 0,len; len = pre.size(); //总的长度 while (vin[i++] != preroot -> val) { lenL++; // 左子树的长度 } lenR = len - lenL - 1; // 右子树的长度 if (len == 0|| lenL == 0 || lenR == 0) return nullptr; vector<int> preleftTree,prerightTree; // 定义前序左子树,前序右子树 vector<int> inleftTree,inrightTree; // 定义中序左子树,中序右子树 for (int m = 0,n = 0; m < lenL; m++) { preleftTree[n++] = pre[1 + m]; //构建前序左子树 } for (int m = 0,n = 0; m < lenL; m++) { inleftTree[n++] = vin[m]; // 构建中序左子树 } for (int m = 0,n = 0; m < lenR; m++) { prerightTree[n++] = pre[1 + m + lenL];// 构建前序右子树 } for (int m = 0,n = 0; m < lenR; m++) { inrightTree[n++] = vin[1 + m + lenL]; // 构建中序右子树 } TreeNode * leftC = new TreeNode(preleftTree[0]); preroot -> left = leftC; TreeNode * rightC = new TreeNode(prerightTree[0]); preroot -> right = rightC; helper(leftC,preleftTree,inleftTree); helper(rightC,prerightTree,inrightTree); return preroot; } };
看了一个别人的
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { int lenp = pre.size(); int leni = in.size(); if(lenp==0 || leni==0 || lenp!=leni) return nullptr; TreeNode *root = new TreeNode(pre[0]); int mid = find(in.begin(),in.end(),pre[0])-in.begin(); vector<int> left_pre(pre.begin()+1,pre.begin()+1+mid); vector<int> left_in(in.begin(),in.begin()+mid); vector<int> right_pre(pre.begin()+1+mid,pre.end()); vector<int> right_in(in.begin()+mid+1,in.end()); root->left = reConstructBinaryTree(left_pre,left_in); root->right = reConstructBinaryTree(right_pre,right_in); return root; } };
标签:logs new ptr 剑指offer 构建 efi binary nod 长度
原文地址:http://www.cnblogs.com/simplepaul/p/6792353.html