给出树的前序遍历和后序遍历,构建树
必须知道一点:
前序遍历是:根、左、右
中序遍历是:左、根、右
后序遍历是:左、右、根
递归构建即可。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: struct TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> in) { if(pre.size()==0)return NULL; TreeNode *root=new TreeNode(pre[0]); int p=0; while(in[p]!=(root->val))p++; root->left = reConstructBinaryTree(vector<int>(pre.begin()+1, pre.begin() + p+ 1), vector<int>(in.begin(),in.begin() + p)); root->right = reConstructBinaryTree(vector<int>(pre.begin() + p+ 1, pre.end() ) , vector<int>(in.begin() + p + 1, in.end() )); return root; } };
原文地址:http://www.cnblogs.com/pk28/
与有肝胆人共事,从无字句处读书。
欢迎关注公众号:
欢迎关注公众号:
![](https://images.cnblogs.com/cnblogs_com/pk28/1069498/o_qrcode_for_gh_db07a03aaa56_344.jpg)