首页 > 代码库 > 给出树的前序遍历和后序遍历,构建树

给出树的前序遍历和后序遍历,构建树

必须知道一点:

前序遍历是:根、左、右

中序遍历是:左、根、右

后序遍历是:左、右、根

递归构建即可。

 

/** * 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;    }};

 

给出树的前序遍历和后序遍历,构建树