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); } }
  • 相关阅读:
    首页效果
    vue 资源精选
    webpack
    常用代码
    超炫效果
    TJ 大神 与 node
    fis webpack 原理对比
    前端自动化测试
    非常强的用户体验的网站功能
    蔡康永: 说话之道
  • 原文地址:https://www.cnblogs.com/du001011/p/11229211.html
Copyright © 2011-2022 走看看