1. 程式人生 > 實用技巧 >leetcode 43:construct-binary-tree-from-inorder

leetcode 43:construct-binary-tree-from-inorder

題目描述

給出一棵樹的中序遍歷和後序遍歷,請構造這顆二叉樹 注意: 保證給出的樹中不存在重複的節點
Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.


示例1

輸入

複製
[2,1,3],[2,3,1]

輸出

複製
{1,2,3}




//不需要輔助函式,簡單易懂
//後序遍歷容器的最後一個數是根節點,中序遍歷的根節點左邊是左子樹,右邊是右子樹,
//後序遍歷左子樹節點值相鄰,右子樹節點值也相鄰。由後序遍歷最後一個值將中序遍歷分成
//左右兩部分,再由這兩部分的size將後序遍歷分成左右兩部分,遞迴即可

class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if(inorder.empty())
return NULL;
int nodeval=postorder[postorder.size()-1];
TreeNode* head=new TreeNode(nodeval);
vector<int>::iterator iter=find(inorder.begin(),inorder.end(),nodeval);
vector<int>leftin=vector<int>(inorder.begin(),iter);
vector<int>rightin=vector<int>(iter+1,inorder.end());
int left=leftin.size();
int right=rightin.size();
if(left>0)
{
vector<int>leftpo=vector<int>(postorder.begin(),postorder.begin()+left);
head->left=buildTree(leftin,leftpo);
}
if(right>0)
{
vector<int>rightpo=vector<int>(postorder.begin()+left,postorder.begin()+left+right);
head->right=buildTree(rightin,rightpo);
}
return head;
}
};