标签:
根据中序遍历和后序遍历树构造二叉树
给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]
返回如下的树:
2
/ \
1 3
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ def buildSubTree(inorder, inBeg, inEnd, postorder, postBeg, postEnd): inLen = len(inorder) postLen = len(postorder) if inBeg == inEnd or inEnd > inLen or postBeg == postEnd or postEnd > postLen: return None root = TreeNode(postorder[postEnd - 1]) pos = inorder.index(root.val) leftLen = pos - inBeg - 1 root.left = buildSubTree(inorder, inBeg, inBeg + leftLen + 1, postorder, postBeg, postBeg + leftLen + 1) root.right = buildSubTree(inorder, inBeg + leftLen + 2, inEnd, postorder, postBeg + leftLen + 1, postEnd - 1) return root class Solution: """ @param inorder : A list of integers that inorder traversal of a tree @param postorder : A list of integers that postorder traversal of a tree @return : Root of a tree """ def buildTree(self, inorder, postorder): # write your code here return buildSubTree(inorder, 0, len(inorder), postorder, 0, len(postorder))
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */ class Solution { /** *@param inorder : A list of integers that inorder traversal of a tree *@param postorder : A list of integers that postorder traversal of a tree *@return : Root of a tree */ public: TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { // write your code here return buildSubTree(inorder.begin(),inorder.end(),postorder.begin(),postorder.end()); } TreeNode *buildSubTree(vector<int>::iterator inBeg, vector<int>::iterator inEnd, vector<int>::iterator postBeg, vector<int>::iterator postEnd) { if(inBeg == inEnd || postBeg == postEnd) { return NULL; }//if TreeNode *root = new TreeNode(*(postEnd - 1)); vector<int>::iterator pos = find(inBeg, inEnd, root->val); if(pos != inEnd) { int leftLen = pos - inBeg - 1; root->left = buildSubTree(inBeg,inBeg+leftLen+1, postBeg,postBeg+leftLen+1); root->right = buildSubTree(inBeg+leftLen+2,inEnd, postBeg+leftLen+1, postEnd -1 ); }//if return root; } };
标签:
原文地址:http://blog.csdn.net/fly_yr/article/details/51685182