zoukankan      html  css  js  c++  java
  • 剑指——重建二叉树

    来源:http://www.cnblogs.com/gl-developer/p/6444280.html

    /** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre==null||in==null||pre.length!=in.length||pre.length<1) return null; return construct(pre,0,pre.length-1,in,0,in.length-1); } public static TreeNode construct(int[] preOrder,int ps,int pe,int[] inOrder,int is,int ie){ //开始位置大于结束位置说明已经处理到叶节点了 if(ps>pe) return null; ///前序遍历第一个数字为当前的根节点 int value=preOrder[ps]; //index为根节点在中序遍历序列中的索引 int index=is; while(index<=ie&&inOrder[index]!=value){ index++; } //System.out.println("当前各参数的数值为->ps:"+ps+" pe:"+pe+" is:"+is+" ie:"+ie+" index:"+index+" rootValue:"+value); //如果在整个中序遍历中没有找到根节点说明输入的数据是不合法的 if(index>ie){ throw new RuntimeException("invalid input"+index); } TreeNode node=new TreeNode(value); //当前节点的左子树的个数为index-is //左子树对应的前序遍历的位置在preOrder[ps+1,ps+index-is] //左子树对应的中序遍历的位置在inOrder[is,index-1] node.left=construct(preOrder,ps+1,ps+index-is,inOrder,is,index-1); //当前节点的右子树的个数为ie-index //右子树对应的前序遍历位置在preOrder[ps+index-is+1,pe] //右子树对应的中序遍历位置在inOrder[index+1,ie] node.right=construct(preOrder,ps+index-is+1,pe,inOrder,index+1,ie); return node; } }
  • 相关阅读:
    2021年Mysql个税计算公式,自定义函数
    安装篇-安装mysql8
    安装篇-安装Nginx
    jsconfig.json配置Webpack别名,识别@
    Avue动态校验表单的必填校验
    renren开源把时间类型Date换为LocalDate报错
    Avue的CRUD最强封装(三)
    Avue-curd通用模板(二)
    Kalman Filter算法详解
    STM32 ADC DMA 中断模式多通道读取ADC转换值
  • 原文地址:https://www.cnblogs.com/Cherrylalala/p/6762646.html
Copyright © 2011-2022 走看看