zoukankan      html  css  js  c++  java
  • LeetCode:105 从前序与中序遍历序列构造二叉树

    本来想自己写个二分查找,想了想好累。。。还是遍历吧

    class Solution {
        
        public TreeNode binaryTree(int[]preorder,int[]inorder,int start,int end,int begin,int fin)
        {
            
            if(start>end){
                return null;
            }
            TreeNode n = new TreeNode(preorder[start]);
            n.left=null;
            n.right=null;
            int mid=0;
            for(int i=begin;i<=fin;i++){
                if(preorder[start]==inorder[i]){
                    mid=i;
                    break;
                }
            }
            n.left = binaryTree(preorder,inorder,start+1,start+mid-begin,begin,mid-1);
            n.right= binaryTree(preorder,inorder,start+mid-begin+1,end,mid+1,fin);
            return n;
        }
    
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            TreeNode t = null;
            if(preorder.length==0||inorder.length==0){
                return null;
            }
            if(preorder==null||inorder==null){
                return null;
            }
            t=binaryTree(preorder,inorder,0,preorder.length-1,0,inorder.length-1);
            
            return t;
        }
    }
  • 相关阅读:
    关于<form>标签
    javaEE学习随笔
    类与接口
    java学习中的一些总结
    java 对象的创建
    jQuery选择器
    CSS学习随笔
    JDBC笔记 二
    Java EE笔记 (1) JDBC
    泛型笔记
  • 原文地址:https://www.cnblogs.com/dloooooo/p/13763512.html
Copyright © 2011-2022 走看看