题目:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
题目来源:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
解题思路:用递归,不断创建节点。
#include<iostream>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
void buildTree(TreeNode *root,vector<int> &postorder,int first1,int last1, vector<int> &inorder,int first2,int last2)
{
if(first1>=last1)
return ;
int i=0;
while(inorder[first2+i]!=postorder[last1])
i++;
if(i>0)//证明有左子树
{
root->left=new TreeNode(postorder[first1+i-1]);
buildTree(root->left,postorder,first1,first1+i-1,inorder,first2,first2+i-1);
}
if(first2+i<last2)//证明有右子树
{
root->right=new TreeNode(postorder[last1-1]);//i到first2的距离为i-first2
buildTree(root->right,postorder,first1+i,last1-1,inorder,first2+i+1,last2);
}
}
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
TreeNode *root=NULL;
if(postorder.empty())
return root;
root=new TreeNode(postorder[postorder.size()-1]);
buildTree(root,postorder,0,postorder.size()-1,inorder,0,inorder.size()-1);
return root;
}
int main()
{
const int N=3;
int A[N]={2,1,3};
int B[N]={2,3,1};
vector<int> postorder(A,A+N);
vector<int> inorder(B,B+N);
buildTree(inorder,postorder);
system("pause");
return 0;
}
注意:当只知道先序和后序时,是没有办法决定中序遍历的,因为此时只能决定第一个定点,没有办法决定左右子树从哪分开,如下:
已知7个节点的二叉树的先根遍历是1 2 4 5 6 3 7(……), 后根遍历是4 6 5 2 7 3 1, 则该二叉树
的可能的中根遍历是( )
A. 4 2 6 5 1 7 3
B. 4 2 5 6 1 3 7
C. 4 2 3 1 5 6 7
D. 4 2 5 6 1 7 3
正确答案是ABD,显然没有办法决定中序遍历。