这道是剑指Offer和PTA原题,早年的代码是这样的:
#数据结构与算法学习笔记#剑指Offer4:先序遍历+中序遍历重建二叉树(Java、C/C++)
#数据结构与算法学习笔记#PTA11:先序遍历+中序遍历转后序遍历/二叉树非递归遍历/二叉树栈遍历(JAVA)
如今重新写一遍,追求的已经不再是简单的通过和最佳思路,而是苛求代码的简洁性和效率。相比于之前的简单递归,在其基础上又增加了哈希表用于存储先序遍历元素在中序遍历数组中的位置,大大提高了区间划分速度。后序遍历+中序遍历->构造二叉树原理相同。
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
根据一棵树的前序遍历与中序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
Given inorder and postorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
根据一棵树的中序遍历与后序遍历构造二叉树。
注意: 你可以假设树中没有重复的元素。
例如,给出
中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
import java.util.HashMap;
/**
*
* Given preorder and inorder traversal of a tree, construct the binary tree.
* You may assume that duplicates do not exist in the tree.
* 根据一棵树的前序遍历与中序遍历构造二叉树。
* 你可以假设树中没有重复的元素。
*
*/
public class ConstructBinaryTreeFromPreorderAndInorderTraversal {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}