题目:根据二叉树的中序于前序遍历结果重建二叉树。
解:用preorder[0]在inorder中找到根的位置,才能把preorder和inorder划分成左右子树。
java:
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length < 1 || inorder.length < 1) return null;
int farValue = preorder[0];
TreeNode far = new TreeNode(farValue);//注!!先把far节点new出来然后dfs far节点左右
int i = 0;
for (; i < inorder.length; i++) {
if (inorder[i] == farValue)
break;
}
int[] leftPreOrder = new int[i];//注!!先把临时数组建立好
int[] leftInOrder = new int[i];
int[] rightPreOrder = new int[preorder.length - i - 1];
int[] rightInOrder = new int[inorder.length - i - 1];
for (int j = 0; j < leftPreOrder.length; j++) {//注!!以临时数组为下标填
leftPreOrder[j] = preorder[j + 1];
leftInOrder[j] = inorder[j];
}
for (int k = 0; k < rightInOrder.length; k++) {
rightPreOrder[k] = preorder[k + i + 1];
rightInOrder[k] = inorder[k + i + 1];
}
far.left = buildTree(leftPreOrder, leftInOrder);
far.right = buildTree(rightPreOrder, rightInOrder);
return far;
}
}
cpp:
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty()) return NULL;
TreeNode *pRoot = new TreeNode(preorder[0]);
vector<int> pre_left, pre_right, in_left, in_right;
int i = 0;
for ( ; i < preorder.size(); i++) {
if (inorder[i] == preorder[0]) break;
}
for (int j = 0; j < i; j++) {
pre_left.push_back(preorder[j + 1]);
in_left.push_back(inorder[j]);
}
for (int j = i + 1; j < preorder.size(); j++) {
pre_right.push_back(preorder[j]);
in_right.push_back(inorder[j]);
}
pRoot->left = buildTree(pre_left, in_left);
pRoot->right = buildTree(pre_right, in_right);
return pRoot;
}
};