zoukankan      html  css  js  c++  java
  • 利用前序遍历和中序遍历构造二叉树

    根据一棵树的前序遍历与中序遍历构造二叉树。
    
    注意:
     你可以假设树中没有重复的元素。
     
     例如,给出
     
     前序遍历 preorder = [3,9,20,15,7]
     中序遍历 inorder = [9,3,15,20,7]
     返回如下的二叉树:
    
         3
        / 
       9  20
         /  
        15   7

    思想:利用分治的思想来解决该题

    具体解题步骤:

      1.根据先序遍历,我们可以知道根节点就是给定数组的第一个元素pre[0],那么我们就可以在中序遍历中找出值等于pre[0]的位置,该位置的前半部分就是左子树,右半部分就是右子树,

      2.重复1,直到遍历完

    实现代码如下:

    public class Solution {
    
        public int preIndex = 0;
    //查找pre[pri]的位置 public int find(int[] inorder, int inbegin,int inend,int val){ for(int i = inbegin;i<=inend;i++){ if(inorder[i] == val) return i; } return -1; }
    public TreeNode buildTreeChild(int[] preorder, int[] inorder, int inbegin,int inend) { if(inbegin>inend) return null; TreeNode root = new TreeNode(preorder[preIndex]); int index = find(inorder,inbegin,inend,preorder[preIndex]); if(index == -1) return null; preIndex++; root.left = buildTreeChild(preorder,inorder,inbegin,index-1); root.right = buildTreeChild(preorder,inorder,index+1,inend); return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { if(preorder == null || inorder == null) return null; return buildTreeChild(preorder,inorder,0,inorder.length-1); } }
  • 相关阅读:
    linux 上安裝lnmp
    html 禁用点击事件
    nftables 是什么? 提供什么功能? 如何使用?
    ESXi主机RAID卡_HBA卡_网卡 型号_固件_驱动查询
    Celery Beat定时任务
    Centos 7/8 安装Rabbit-MQ
    Celery 最佳实践
    Django 3.0 + Celery 4.4 + RabbitMQ
    C语言Socket示例
    深入理解计算机系统 — 读书笔记
  • 原文地址:https://www.cnblogs.com/du001011/p/11229211.html
Copyright © 2011-2022 走看看