AcWing18:重建二叉树(Java实现)

18题目:

根据前序遍历和中序遍历,求二叉树

思路:

递归思想比较容易想,主要是递归过程中的对于前序遍历和中序遍历剩余数组边界的确定

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int[] preorder;//前序遍历数组
    int[] inorder;//中序遍历数组
    HashMap<Integer,Integer> map;//用于寻找中序遍历中的根节点下标
    
    public TreeNode dfs(int pl,int pr,int il,int ir){
        if(pl > pr) return null;
        //根节点
        TreeNode root = new TreeNode(preorder[pl]);
        int k = map.get(root.val);//根节点在中序遍历中的下标
        //左子树
        //左子树的前序遍历数组:
        //pl+1好理解,k-il为根据中序数组中,根节点左边的节点就是左子树的所有节点,k-il为
        //左子树的节点数目,pl+k-il为左子树节点的末尾,都是起始节点(pl)+数量(k+il)的思路
        root.left = dfs(pl+1,pl+k-il,il,k-1);
        //右子树
        root.right = dfs(pl+k-il+1,pr,k+1,ir);
        return root;
    }
    
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        this.preorder = preorder;
        this.inorder = inorder;
        map = new HashMap<Integer,Integer>();
        for(int i=0;i<inorder.length;i++)map.put(inorder[i],i);
        return dfs(0,preorder.length-1,0,inorder.length-1);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值