二叉树的构建必须要有中序遍历,另外还需要前序和后续中的一种。下面分别是有前序和中序、后续和中序采用递归方法构建二叉树的过程
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { if(preorder.empty()) return nullptr; int n = preorder.size(); int rootVal = preorder[0]; TreeNode* root = new TreeNode(rootVal); vector<int> leftIn(inorder.begin(),find(inorder.begin(),inorder.end(),rootVal)); int leftSize = leftIn.size(); vector<int> leftPre(preorder.begin()+1,preorder.begin()+1+leftSize); vector<int> rightIn(inorder.begin()+leftSize+1,inorder.end()); vector<int> rightPre(preorder.begin()+leftSize+1,preorder.end()); root->left= buildTree(leftPre,leftIn); root->right = buildTree(rightPre,rightIn); return root; } };
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution{ public: TreeNode* buildTree(vector<int>& inorder,vector<int>& postOrder){ if(postOrder.empty()) return nullptr; int n = postOrder.size(); int rootVal = postOrder[n-1]; TreeNode* root = new TreeNode(rootVal); vector<int> leftIn(inorder.begin(),find(inorder.begin(),inorder.end(),rootVal)); int leftSize = leftIn.size(); vector<int> leftPost(postOrder.begin(),postOrder.begin()+leftSize); vector<int> rightIn(inorder.begin()+leftSize+1,inorder.end()); vector<int> rightPost(postOrder.begin()+leftSize,postOrder.end()-1); root->left = buildTree(leftIn,leftPost); root->right = buildTree(rightIn,rightPost); return root; } };