标签:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Tree Array Depth-first Search
这道题给了你二叉树前序遍历和中序遍历的结果(以vector的形式给的,其中没有那些不存在的点),所以在前序遍历中第一个肯定是根节点
这道题采用递归的方法来做,因为在前序遍历中的第一个点,在中序遍历中,它的左边为其左子树,右边为其右子树,这样依次向下递归就可以构造出了二叉树。
下面是AC的解法
#include<iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
/*找到a在vec中的位置*/
int laocation_vector(vector<int>& vec,int a,int i,int j)
{
for(int k=i;k<=j;++k)
if(vec[k]==a)
return k;
return -1;
}
/*i,j是范围,k是开始计算第几个*/
void pre_construct(vector<int>& preorder,vector<int>& inorder,TreeNode** root,int i,int j,int& k)
{
if(k>=preorder.size())
{
*root=NULL;
return;
}
int loacte_in=laocation_vector(inorder,preorder[k],i,j);
if(loacte_in<i||loacte_in>j)
{
*root=NULL;
return;
}
*root=(TreeNode*)malloc(sizeof(TreeNode));
(*root)->val=preorder[k];
k++;
pre_construct(preorder,inorder,&(*root)->left,i,loacte_in-1,k);
pre_construct(preorder,inorder,&(*root)->right,loacte_in+1,j,k);
return;
}
/*这个函数来主要调用*/
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
{
TreeNode* root=NULL;
if(preorder.size()==NULL)
return root;
int k=0;
pre_construct(preorder,inorder,&root,0,(preorder.size()-1),k);
return root;
}
int main()
{
vector<int> vec_pre;
vector<int> vec_in;
vec_pre.push_back(1),vec_pre.push_back(2);
vec_in.push_back(2),vec_in.push_back(1);
TreeNode* root;
root=buildTree(vec_pre,vec_in);
}
leetcode_105题——Construct Binary Tree from Preorder and Inorder Traversal(树,递归)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4474045.html