栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【浅刷Java数据结构】LeetCode 105 从前序与中序遍历构建二叉树

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【浅刷Java数据结构】LeetCode 105 从前序与中序遍历构建二叉树

链接: LeetCode 105 从前序与中序遍历构建二叉树


总体思路:

二叉树 = 根结点 + 左子树 + 右子树

  1. 对于前序遍历中的每个结点,他们都可以看作一个根节点,他们都有自己的左右子树
  2. 每个结点之间的关系呢,就可以根据中序遍历断定

代码:

class Solution {
    public int preIndex=0;
    public TreeNode buildTreeChild(int [] preorder, int[] inorder,int inbegin,int inend){
        if(inbegin>inend){//说明此时没有左树或者右树
            return null;
        }

        TreeNode root = new TreeNode(preorder[preIndex]);//创建根节点

        int rootIndex=findIndex(inorder,preorder[preIndex]);
        preIndex++;
        root.left=buildTreeChild(preorder,inorder,inbegin,rootIndex-1);//创建左子树
        root.right=buildTreeChild(preorder,inorder,rootIndex+1,inend);//创建右子树
        return root;
    }
    public int findIndex(int[] inorder,int val){
        for(int i=0;i
            if(inorder[i]==val){
                return i;
            }
        }
        return -1;
    }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTreeChild(preorder,inorder,0,inorder.length-1);
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/933274.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号