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;
        }
    }
  • 相关阅读:
    图片处理
    define 常量的定义和读取
    curl
    stream_get_contents 和file_get_content的区别
    php flock 文件锁
    字符串函数
    php 常量
    debug_backtrace()
    pathlib模块替代os.path
    Python中对 文件 的各种骚操作
  • 原文地址:https://www.cnblogs.com/dloooooo/p/13763512.html
Copyright © 2011-2022 走看看