zoukankan      html  css  js  c++  java
  • 8 根据前序遍历和中序遍历得到二叉树

    1. /** 
    2.  * 前序遍历和中序遍历创建二叉树  
    3.           Pre 前序遍历的数组 In 中序遍历的数组 lpre 前序遍历数组开始位置 hpre前序遍历结束位置 
    4.  * lin前序遍历数组开始位置 hin前序遍历结束位置 
    5.  */  
    6. @Override  
    7. public TreeNode PreInCreat(int[] Pre, int[] In, int lpre, int hpre, int lin, int hin) {  
    8.     TreeNode root = new TreeNode(0);  
    9.     if (Pre.length == 0 || In.length == 0) {  
    10.         return null;  
    11.     }  
    12.     root.val = Pre[lpre];  
    13.     int i;  
    14.     for (i = lin; In[i] != Pre[lpre]; i++)  
    15.         ;// 得到中序遍历数组的根节点位置  
    16.     int lleng = i - lin;// 左边子树的长度  
    17.     int rleng = hin - i;// 右边子树的长度  
    18.     
    19.     if (lleng > 0) {  
    20.         root.leftchild = PreInCreat(Pre, In, lpre + 1, lpre + lleng, lin, lin + lleng - 1);  
    21.     
    22.     } else {  
    23.         root.leftchild = null;  
    24.     }  
    25.     if (rleng > 0) {  
    26.         root.rightchild = PreInCreat(Pre, In, hpre - rleng + 1, hpre, hin - rleng + 1, hin);  
    27.     
    28.     } else {  
    29.         root.rightchild = null;  
    30.     }  
    31.     
    32.     return root;  
    33. }  
  • 相关阅读:
    c++ 视频和教程下载站点
    SQL超时解决方法
    初学者必备:C++经典入门详细教程
    人生致命的八个经典问题
    字长与字节
    typedef用法(三)
    遍历搜索注册表
    数据库连接字符串大全 之 SQL服务器篇
    十五个步骤收获学习的习惯
    谈基于.net平台windows开发中的模式窗体.NET教程,.NET Framework
  • 原文地址:https://www.cnblogs.com/wwjldm/p/6919060.html
Copyright © 2011-2022 走看看