Description:
Given (pre/post)order and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
——————————————————————————————————————————————————————————————————————————
Solution:
题意:通过前序遍历和中序遍历,或后序遍历和中序遍历,构造一棵二叉树。
思路:递归构造。
由前序遍历和中序遍历:
/**
* Definition for a binary tree node.
* 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) {
this->preorder = preorder;
this->inorder = inorder;
return constructTree(0, 0, inorder.size() - 1);
}
TreeNode* constructTree(int preStart, int inStart, int inEnd) {
if (preStart >= preorder.size() || inStart > inEnd)
return NULL;
int curIndex = 0;
TreeNode* curRoot = new TreeNode(preorder[preStart]);
for (int i = inStart; i <= inEnd; i++) {
if (preorder[preStart] == inorder[i]) {
curIndex = i;
break;
}
}
curRoot->left = constructTree(preStart + 1, inStart, curIndex - 1);
curRoot->right = constructTree(preStart + curIndex - inStart + 1, curIndex + 1, inEnd);
return curRoot;
}
private:
vector<int> preorder, inorder;
};
由后序遍历和中序遍历:
/**
* Definition for a binary tree node.
* 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) {
this->postorder = postorder;
this->inorder = inorder;
return constructTree(postorder.size() - 1, 0, inorder.size() - 1);
}
TreeNode* constructTree(int postStart, int inStart, int inEnd) {
if (postStart < 0 || inStart > inEnd)
return NULL;
int curIndex = 0;
TreeNode* curRoot = new TreeNode(postorder[postStart]);
for (curIndex = inStart; curIndex <= inEnd; curIndex++)
if (postorder[postStart] == inorder[curIndex])
break;
curRoot->left = constructTree(postStart - (inEnd - curIndex) - 1, inStart, curIndex - 1);
curRoot->right = constructTree(postStart - 1, curIndex + 1, inEnd);
return curRoot;
}
private:
vector<int> postorder, inorder;
};