标签:des you traversal treenode ++ ons new http root
根据前序遍历和中序遍历树构造二叉树.
你可以假设树中不存在相同数值的节点
给出中序遍历:[1,2,3]
和前序遍历:[2,1,3]
. 返回如下的树:
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 {
public:
/**
* @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
*/
TreeNode * buildTree(vector<int> &preorder, vector<int> &inorder) {
// write your code here
int a=inorder.size();
int b=preorder.size();
if (a!=b||a==0||b==0)
{
return NULL;
}
return buildtr(preorder,inorder,0,b-1,0,a-1);
}
TreeNode *buildtr(vector<int> &preorder, vector<int> &inorder,int prst,int pred,int inst,int ined)
{
if (inst>ined)
{
return NULL;
}
int i=inst;
while(i<=ined&&inorder[i]!=preorder[prst])
{
i++;
}
TreeNode * root=new TreeNode(preorder[prst]);
root->left=buildtr(preorder,inorder,prst+1,prst+i-inst,inst,i-1);//左子树,递归时弄清楚索引参数;
root->right=buildtr(preorder,inorder,prst+i-inst+1,prst+ined-inst,i+1,ined);//右子树,递归时弄清楚索引参数;
return root;
}
};
标签:des you traversal treenode ++ ons new http root
原文地址:https://www.cnblogs.com/Tang-tangt/p/9273570.html