标签:null duplicate 细节 理解 follow The order || help
算法描述:
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,15,7,20,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, 0, 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, postorder, ps, ps - (is-pos+1)); node -> right = helper(inorder, pos+1, ie, postorder, ps - (is-pos+1)+1, pe-1); return node; }
LeetCode-106-Construct Binary Tree from Inorder and Postorder Traversal
标签:null duplicate 细节 理解 follow The order || help
原文地址:https://www.cnblogs.com/nobodywang/p/10349592.html