# 从前序与中序遍历序列构造二叉树

前序遍历 preorder = [3,9,20,15,7]

3
/ \
9  20
/  \
15   7


struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


 TreeNode *buildDFSTree(vector<int> &preorder,int prel, int preh, vector<int> &inorder, int inl, int inh)
{
//前序遍历的第一个节点是当前树的根节点
//创建根节点
TreeNode *root = new TreeNode(preorder[prel]);
int i, leftn, rightn;
//找到根节点在中序遍历中的位置
for(i = 0; inorder[i] != preorder[prel]; i++);
//左子树节点个数
leftn = i - inl;
//右子树节点个数
rightn = inh - i;
//递归构建左子树
//根节点的左子节点是其左子树的根节点
if(leftn > 0)
root->left = buildDFSTree(preorder,prel+1,prel+leftn,inorder,inl,i-1);
//递归构建右子树
//根节点的右子节点是其右子树的根节点
if(rightn > 0)
root->right = buildDFSTree(preorder,prel+leftn+1,inh,inorder,i+1,inh);
return root;
}

TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
TreeNode *root = NULL;
if(preorder.size() > 0)
root = buildDFSTree(preorder,0, preorder.size()-1, inorder,0, inorder.size()-1);
return root;
}


©️2019 CSDN 皮肤主题: 数字20 设计师: CSDN官方博客