题目描述
输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
本题知识点: 树 dfs 数组
思路:根据先序遍历的特点,每次遍历到的第一个元素即为根节点值,接着需要确定其左右子树,寻找该元素在中序遍历序列的位置,即可得到左右子树的中序遍历序列,根据长度信息,可以得出左右子树的前序遍历序列,左右子树先序的第一个元素即为根节点的左右孩子结点,依次递归即可
C++实现:
class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if(pre.size()>0&&vin.size()>0){ return reConstructBinaryTree2(pre,vin,0,pre.size()-1,0,vin.size()-1); } return NULL; } TreeNode* reConstructBinaryTree2(vector<int> pre,vector<int> vin, int preStart,int preEnd, int vinStart,int vinEnd){ if(preStart>preEnd || vinStart>vinEnd ) return NULL; TreeNode* root = new TreeNode(pre[preStart]); vector<int>::iterator it = find(vin.begin(),vin.end(),pre[preStart]); int mid = &*it-&vin[0]; int len = mid - vinStart; root->left = reConstructBinaryTree2(pre,vin,preStart+1,preStart+len,vinStart,mid-1); root->right = reConstructBinaryTree2(pre,vin,preStart+len+1,preEnd,mid+1,vinEnd); return root; } };
记得中间变量要写在里面,不能写在递归函数外面
查看剑指offer之后修改了递归条件
class Solution { public: TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { if(pre.size()>0&&vin.size()>0){ return reConstructBinaryTree2(pre,vin,0,pre.size()-1,0,vin.size()-1); } return NULL; } TreeNode* reConstructBinaryTree2(vector<int> pre,vector<int> vin, int preStart,int preEnd, int vinStart,int vinEnd){ TreeNode* root = new TreeNode(pre[preStart]); if(preStart == preEnd && vinStart == vinEnd && pre[preStart]==vin[vinStart]){ return root; } vector<int>::iterator it = find(vin.begin(),vin.end(),pre[preStart]); int mid = &*it-&vin[0]; int len = mid - vinStart; if(len>0) root->left = reConstructBinaryTree2(pre,vin,preStart+1,preStart+len,vinStart,mid-1); if(len<preEnd - preStart) root->right = reConstructBinaryTree2(pre,vin,preStart+len+1,preEnd,mid+1,vinEnd); return root; } };
java实现:
public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre.length == 0 || in.length == 0 || pre.length != in.length) return null; return reConstructBinaryTree2(pre,in,0,pre.length-1,0,in.length-1); } public TreeNode reConstructBinaryTree2(int [] pre,int [] in, int preStart,int preEnd, int vinStart,int vinEnd){ TreeNode root = new TreeNode(pre[preStart]); if(preStart == preEnd&&vinStart == vinEnd && pre[preStart] == in[vinStart]) return root; int mid = find(in,pre[preStart]); int leftLen = mid - vinStart; if(leftLen > 0)//存在左子树,即左子树序列长度大于0 root.left = reConstructBinaryTree2(pre,in,preStart+1,preStart+leftLen,vinStart,mid-1); if(leftLen < vinEnd - vinStart)//存在右子树 root.right = reConstructBinaryTree2(pre,in,preStart+leftLen+1,preEnd,mid+1,vinEnd); return root; } public int find(int[] in,int preStart){ for(int i=0;i<in.length;i++){ if(in[i]==preStart) return i; } return -1; } }