已知前序、中序建立二叉树
class Soluetion {
int pos;
public:
TreeNode *tree(int left, int right, vector<int> &preorder, vector<int> &inorder) {
if (left > right)return nullptr;
int t = preorder[pos++];
int location;
for (int i = 0; i < inorder.size(); i++) {
if (inorder[i] == t) {
location = i;
break;
}
}
TreeNode *root = new TreeNode(t);
root->left = tree(left, location - 1, preorder, inorder);
root->right = tree(location + 1, right, preorder, inorder);
return root;
};
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int size = inorder.size();
if (size == 0)return nullptr;
pos = inorder.size() - 1;
return tree(0, inorder.size() - 1, preorder,inorder);
}
};
已知中序、后序建立二叉树
这一段代码与上一段有明显的区别,最大的区别在于上一段代码先递归左树后递归右树,后一段代码先递归右树后递归左树。而这正是前序遍历和后序遍历的特点所决定的
class Solution {
public:
int pos;
TreeNode *tree(int left, int right, vector<int> &inorder, vector<int> &postorder) {
if(left>right||pos==-1)return nullptr;
int t=postorder[pos--];
int location;
for (int i = 0; i < inorder.size(); i++) {
if (inorder[i] == t) {
location = i;
break;
}
}
TreeNode *root = new TreeNode(t);
root->right = tree(location + 1, right, inorder, postorder);
root->left = tree(left, location - 1,inorder, postorder);
return root;
}
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
int size = inorder.size();
if (size == 0)return nullptr;
pos = inorder.size() - 1;
return tree(0, inorder.size() - 1, inorder, postorder);
}
};