剑指 Offer 07. 重建二叉树
题目链接
前序遍历:根节点->左子树->右子树
中序遍历:左子树->根节点->右子树
前序遍历的第一个节点是根节点,然后根据根节点在中序遍历数组中的位置,该位置左边是左子树的节点数量,该位置右边是右子树的节点数量。
C++:
/**
* 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:
unordered_map<int, int> map;
vector<int> preorder;
TreeNode* DFS(int prestart, int preend, int instart, int inend)
{
if(prestart > preend)
return nullptr;
int num = preorder[prestart];
TreeNode* root = new TreeNode(num);
if(prestart == preend) //如果该树只有一个节点
return root;
int rootindex = map[num];
int leftcount = rootindex-instart;
int rightcount = inend-rootindex;
TreeNode* leftnode = DFS(prestart+1, prestart+leftcount, instart, rootindex-1);
TreeNode* rightnode = DFS(preend-rightcount+1, preend, rootindex+1, inend);
root->left = leftnode;
root->right = rightnode;
return root;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int prelen = preorder.size();
if(prelen == 0) {
return nullptr;
}
this->preorder = preorder;
for(int i = 0; i < prelen; i++)
{
map[inorder[i]] = i;
}
return DFS(0, prelen-1, 0, prelen-1);
}
};
官方给的java代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || preorder.length == 0) {
return null;
}
Map<Integer, Integer> indexMap = new HashMap<Integer, Integer>();
int length = preorder.length;
for (int i = 0; i < length; i++) {
indexMap.put(inorder[i], i);
}
TreeNode root = buildTree(preorder, 0, length - 1, inorder, 0, length - 1, indexMap);
return root;
}
public TreeNode buildTree(int[] preorder, int preorderStart, int preorderEnd, int[] inorder, int inorderStart, int inorderEnd, Map<Integer, Integer> indexMap) {
if (preorderStart > preorderEnd) {
return null;
}
int rootVal = preorder[preorderStart];
TreeNode root = new TreeNode(rootVal);
if (preorderStart == preorderEnd) {
return root;
} else {
int rootIndex = indexMap.get(rootVal);
int leftNodes = rootIndex - inorderStart, rightNodes = inorderEnd - rootIndex;
TreeNode leftSubtree = buildTree(preorder, preorderStart + 1, preorderStart + leftNodes, inorder, inorderStart, rootIndex - 1, indexMap);
TreeNode rightSubtree = buildTree(preorder, preorderEnd - rightNodes + 1, preorderEnd, inorder, rootIndex + 1, inorderEnd, indexMap);
root.left = leftSubtree;
root.right = rightSubtree;
return root;
}
}
}
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/mian-shi-ti-07-zhong-jian-er-cha-shu-by-leetcode-s/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
不递归不知道C++传vector是多么浪费时间!!!
这里有一个坑,就是如果C++版本像java一样传递数组preorder, inorder,还有hashmap,会在最后一个数据超时。
如果不传hashmap:
如果也不传inorder:
如果也不传preorder:
如果对你有帮助的话,请点个赞哦!