LeetCode-106-Construct Binary Tree from Inorder and Postorde
发布时间:2020-12-14 04:26:12 所属栏目:大数据 来源:网络整理
导读:算法描述: Given inorder and postorder traversal of a tree,construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example,given inorder =?[9,3,15,20,7]postorder = [9,7,3] Return the following binary t
算法描述: Given inorder and postorder traversal of a tree,construct the binary tree. Note: For example,given inorder =?[9,3,15,20,7] postorder = [9,7,3] Return the following binary tree: 3 / 9 20 / 15 7 解题思路:理解原理,注意细节。 TreeNode* buildTree(vector<int>& inorder,vector<int>& postorder) { return helper(inorder,0,inorder.size()-1,postorder,postorder.size()-1); } TreeNode* helper(vector<int>& inorder,int is,int ie,vector<int>& postorder,int ps,int pe){ if(is > ie || ps > pe) return nullptr; TreeNode* node = new TreeNode(postorder[pe]); int pos = 0; for(int i=is; i <= ie; i++){ if(postorder[pe]==inorder[i]){ pos = i; break; } } node -> left = helper(inorder,is,pos-1,ps,ps - (is-pos+1)); node -> right = helper(inorder,pos+1,ie,ps - (is-pos+1)+1,pe-1); return node; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |