105. Construct Binary Tree from Preorder and Inorder Traversal

本文详细介绍了如何使用前序遍历和中序遍历数组来生成二叉树的方法。通过理解前序和中序遍历的特点,文章提供了一个递归算法,该算法首先找到根节点,然后确定左右子树的范围,最后递归地构建整棵树。

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;

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值