Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
给一个前序遍历数组和一个中序遍历的数组,生成一颗二叉树。
1、根据前序遍历的特点,前序遍历数组的第一个值是整棵树的根节点。
2、根据根节点值到中序遍历数组中寻找,假设在中序遍历数组中的索引为i,则0到i-1为根节点的左子树的中序遍历值。i+1到最后是根节点右子树的中序遍历值。
3、则前序遍历数组中的1到i项为根节点左子树的前序遍历值,i+1到最后是右子树的前序遍历值。
4、递归调用。
public TreeNode buildTree(int[] preorder, int[] inorder) {
List<Integer> preList = new ArrayList<>();
List<Integer> midList = new ArrayList<>();
for (int i : preorder) {
preList.add(i);
}
for (int i : inorder) {
midList.add(i);
}
return buildTree(preList, midList);
}
private TreeNode buildTree(List<Integer> preList, List<Integer> midList){
if(preList.isEmpty() || midList.isEmpty())
return null;
int value = preList.get(0);
TreeNode root = new TreeNode(value);
int len = midList.indexOf(value);
root.left = buildTree(preList.subList(1, len+1), midList.subList(0, len));
root.right = buildTree(preList.subList(len+1, preList.size()), midList.subList(len+1, midList.size()));
return root;
}
本文详细介绍了如何使用前序遍历和中序遍历数组来生成二叉树的方法。通过理解前序和中序遍历的特点,文章提供了一个递归算法,该算法首先找到根节点,然后确定左右子树的范围,最后递归地构建整棵树。
3499

被折叠的 条评论
为什么被折叠?



