【数据结构刷题java】根据前序遍历和中序遍历构造二叉树

【数据结构刷题java】根据前序遍历和中序遍历构造二叉树

[题目链接](105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com))

前序遍历的第一个都是根节点,所以从中序遍历中找到该根节点,根节点的左边就是左子树,根节点的右边就是右子树。

所以,就创建根节点,根节点的left,right就重复上面的行为。

class Solution {
    public int preIndex;
    public int findInOrderIndex(int target,int[] inorder,int begin,int end){
        for(int i=begin;i<=end;i++){
            if(inorder[i]==target)
                return i;
        }
        return -1;
    }
    public TreeNode createTree(int[] preorder,int[] inorder,int begin,int end){
        //如果begin<end的话,就说明是到空节点了
        if(begin>end) return null;
        //找到中序遍历中的根节点的下标
        int inIndex=findInOrderIndex(preorder[preIndex],inorder,begin,end);
        //如果,没有找到,就返回null
        if(inIndex==-1) return null;
        //如果找到了,就创建根节点
        TreeNode root=new TreeNode(preorder[preIndex]);
        //再分别去递归遍历左子树和右子树
        preIndex++;
        root.left=createTree(preorder,inorder,begin,inIndex-1);
        root.right=createTree(preorder,inorder,inIndex+1,end);
        return root;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder==null||inorder==null) return null;
        return createTree(preorder,inorder,0,preorder.length-1);
    }
}

还有一个根据中序遍历和后序遍历的题和这个的 解题套路差不多

[中序和后序](106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode) (leetcode-cn.com))

这里就只展示代码了

class Solution {
    public int postIndex;
    public int findInOrderIndex(int target,int[] inorder,int begin,int end){
        for(int i=begin;i<=end;i++){
            if(inorder[i]==target)
                return i;
        }
        return -1;
    }
    public TreeNode createTree(int[] postorder,int[] inorder,int begin,int end){
        //如果begin<end的话,就说明是到空节点了
        if(begin>end) return null;
        //找到中序遍历中的根节点的下标
        int inIndex=findInOrderIndex(postorder[postIndex],inorder,begin,end);
        //如果,没有找到,就返回null
        if(inIndex==-1) return null;
        //如果找到了,就创建根节点
        TreeNode root=new TreeNode(postorder[postIndex]);
        //再分别去递归遍历左子树和右子树
        postIndex--;
        root.right=createTree(postorder,inorder,inIndex+1,end);
        root.left=createTree(postorder,inorder,begin,inIndex-1);
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(postorder==null||inorder==null) return null;
        postIndex=postorder.length-1;
        return createTree(postorder,inorder,0,postorder.length-1);
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值