• 二叉树重建-递归


    package JianZhioffer;
    // 输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
    //递归,进入helperZ之前用整体进入后分左右
    public class test07 {
        public static void main(String[] args) {
           int []preorder={3,9,20,15,7};
           int []inorder={9,3,15,20,7};
           TreeNode tr=buildTree(preorder, inorder);
           int x=0;
        }
        public static TreeNode buildTree(int[] preorder, int[] inorder) {
            if(preorder.length==0||inorder.length==0){
                return null;
            }
            
            TreeNode result=helper(0, preorder.length-1, 0,inorder.length-1,preorder, inorder);
            return result;
        }
        public static TreeNode helper(int prestart,int preend,int instart,int inend,int []preorder,int []inorder){
            
            if( prestart>preend){
                return null;
            }
            TreeNode tr=new TreeNode(preorder[prestart]);
            if(prestart==preend){
                return tr;
            }
            
            int r=preorder[prestart];
            int k=0;
            for(int i=instart;i<=inend;i++){
                if(inorder[i]==r){
                    k=i;
                    break;
                }
            }
            int x=k-instart;
            int y=inend-k;
            tr.left=helper(prestart+1, prestart+x,instart,k-1, preorder, inorder);
            tr.right=helper(preend-y+1, preend,k+1,inend, preorder, inorder);
    
            return tr;
        }
    }
  • 相关阅读:
    AngularJS7那些不得不说的事故
    Python和C++的混合编程(使用Boost编写Python的扩展包)
    为OPENCV添加freetype支持并显示中文字符(在mac上编译opencv及contrib库)
    OpenProject基础使用介绍
    负载均衡
    如何搭建wordpress ,wecenter
    nginx 模块
    Nginx
    http 协议
    ssh
  • 原文地址:https://www.cnblogs.com/jieyi/p/14201706.html
Copyright © 2020-2023  润新知