前序和中序遍历来构建二叉树

这里写图片描述

 import java.util.*;
 class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode(int x) { val = x; }
  }

public class Solution {
    HashMap<Integer,Integer>map=new HashMap<>();
    public TreeNode buildTree(int[] preorder, int[] inorder) {
         for(int i=0;i<preorder.length;i++)
              map.put(inorder[i],i);

        return BuildBinaryTree(0,0,inorder.length-1,preorder,inorder);
    }

     public TreeNode  BuildBinaryTree(int preStart,int inStart,int inEnd,int []preorder,int[]inorder){
         if(preStart>preorder.length-1||inStart>inEnd) 
             return null;
         TreeNode root=new TreeNode(preorder[preStart]);
         int index=map.get(root.val);
         root.left=BuildBinaryTree(preStart+1,inStart,index-1,preorder,inorder);
         root.right=BuildBinaryTree(preStart+index-inStart+1,index+1,inEnd,preorder,inorder);
         return root;
     }

    public static void main(String[]args){
       System.out.println("Hello World!");
    }
}

猜你喜欢

转载自blog.csdn.net/u012017783/article/details/81229458