标签:
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { 13 /* 14 解题思路: 15 1、构建递归调用函数,将先序遍历数组pre和中序遍历数组in, 及其对应的起始位置和长度作为实参 16 */ 17 TreeNode *root=constructBinaryTree(pre,0,pre.size()-1,in,0,in.size()-1); 18 return root; 19 } 20 TreeNode *constructBinaryTree(vector<int> pre,int pre_start,int pre_end,vector<int> in,int in_start,int in_end){ 21 //递归退出的条件 22 if(pre_start>pre_end||in_start>in_end){ 23 return NULL; 24 } 25 TreeNode *root=(TreeNode *)malloc(sizeof(TreeNode));//创建根节点 26 root->val=pre[pre_start]; 27 for(int i=in_start;i<=in_end;i++){ 28 if(pre[pre_start]==in[i]){ 29 root->left=constructBinaryTree(pre,pre_start+1,pre_start+(i-in_start),in,in_start,i-1);//将左子树传入(数组,及其对应的下标) 30 root->right=constructBinaryTree(pre,pre_start+i-in_start+1,pre_end,in,i+1,in_end); //将右子树传入 31 } 32 } 33 return root; 34 } 35 };
标签:
原文地址:http://www.cnblogs.com/dingou/p/5830572.html