该问题用递归的思路很好解决,每一次取前序序列的首元素作为当前子树的根节点,然后在中序序列中找到对应的节点,以此可以确定根节点对应的左子树和右子树的序列长度,递归构造根节点的左子树和右子树即可。
TreeNode *execBuild(vector<int> &preorder, int prestart, int preend, vector<int> &inorder, int instart, int inend){ TreeNode *result = new TreeNode(preorder[prestart]); if(prestart == preend){ return result; } int i; for( i = instart; i <= inend; i++){ if(inorder[i] == preorder[prestart]) break; } if(i == instart){ result -> left = nullptr; }else{ result -> left = execBuild(preorder, prestart + 1, prestart + i - instart, inorder, instart, i - 1); } if(i == inend){ result -> right = nullptr; }else{ result -> right = execBuild(preorder, preend - (inend - i) + 1, preend, inorder, i + 1, inend); } return result; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // write your code here int size = preorder.size(); if(size < 1) return nullptr; return execBuild(preorder, 0, size - 1, inorder, 0, size - 1); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/ny_mg/article/details/48136549