根據中序遍歷和后序遍歷樹構造二叉樹
注意事項
你可以假設樹中不存在相同數值的節點
樣例
給出樹的中序遍歷: [1,2,3] 和后序遍歷: [1,3,2]
返回如下的樹:
2
/ \
1 3
思路:與中序遍歷和前序遍歷構造二叉樹的過程類似。只不過對於后序遍歷來說。根節點是最后一個被訪問的節點;
或者,可以先將先序遍歷序列逆序,然后過程就與中序遍歷和前序遍歷構造二叉樹的過程完全一樣了;
注意:最后遞歸的時候,一定不要把中序遍歷的序列和后續遍歷的序列弄反了。血的教訓,不要直接復制代碼,順着思路過一遍.
/** * 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 if(postorder.size()==0||inorder.size()==0){ return NULL; } if(postorder.size()!=inorder.size()){ return NULL; } vector<int> inorder_l,inorder_r,postorder_l,postorder_r; int root_index=-1; int len = postorder.size(); TreeNode* root=new TreeNode(postorder[len-1]); // 在中序隊列中找出根節點位置 for(int i=0;i<len;i++){ if(postorder[len-1]==inorder[i]){ root_index=i; break; } } // 左右子樹的后序、中序隊列 for(int i=0; i<root_index; i++) { postorder_l.push_back(postorder[i]); inorder_l.push_back(inorder[i]); } for(int i=root_index+1; i<inorder.size(); i++) { postorder_r.push_back(postorder[i-1]); inorder_r.push_back(inorder[i]); } root->left=buildTree(inorder_l, postorder_l); root->right=buildTree(inorder_r, postorder_r); return root; } };