标签:面试题 psi TreeNode 07 int riii isi 二叉树 root
题目:
解答:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *buildTree(vector<int> &iorder, int isi, int iei, vector<int> &porder, int psi, int pei) 13 { 14 if(iei - isi < 0 || iei - isi != pei - psi) 15 { 16 return NULL; 17 } 18 19 //the porder[pei] is the root of this tree 20 21 TreeNode *root = new TreeNode(porder[pei]); 22 23 //find the root in the iorder to seperate it into left sub tree and right sub tree 24 //root index in inorder array 25 26 int riii = -1; 27 for(int i = isi; i <= iei; ++i) 28 { 29 if(iorder[i] == root->val) 30 { 31 riii = i; 32 break; 33 } 34 } 35 if(riii == -1) 36 { 37 return root;//error 38 } 39 40 int lnodes = riii - isi; 41 42 //for the left sub tree 43 //the isi to riii - 1 in inorder array will be it's inorder traversal 44 //and the psi to psi + lnodes - 1 in postorder array will be it's post order traversal 45 46 root->left = buildTree(iorder, isi, riii - 1, porder, psi, psi + lnodes - 1); 47 48 //for the right sub tree is similary to the left 49 50 root->right = buildTree(iorder, riii + 1, iei, porder, psi + lnodes, pei - 1); 51 52 return root; 53 } 54 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) 55 { 56 return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() -1); 57 } 58 };
标签:面试题,psi,TreeNode,07,int,riii,isi,二叉树,root 来源: https://www.cnblogs.com/ocpc/p/12856591.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。