Java实现-中序遍历和后续遍历构建二叉树

来源:互联网 发布:c 编程软件 编辑:程序博客网 时间:2024/06/05 09:51


/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */  public class Solution {    /**     *@param inorder : A list of integers that inorder traversal of a tree     *@param postorder : A list of integers that postorder traversal of a tree     *@return : Root of a tree     */    public TreeNode buildTree(int[] inorder, int[] postorder) {        // write your code here        TreeNode root=null;root=inAndPost(inorder, postorder);return root;    }    private static TreeNode inAndPost(int []inorder,int []postorder){if(inorder.length==0||postorder.length==0){return null;}int val=postorder[postorder.length-1];TreeNode root=new TreeNode(val);int index=0;for(int i=0;i<inorder.length;i++){if(val==inorder[i]){index=i;}}int leftInOrder[]=Arrays.copyOfRange(inorder, 0, index);int rightInOrder[]=Arrays.copyOfRange(inorder, index+1, inorder.length);int leftPostOrder[]=Arrays.copyOfRange(postorder, 0, index);int rightPostOrder[]=Arrays.copyOfRange(postorder, index, postorder.length-1);root.left=inAndPost(leftInOrder, leftPostOrder );    root.right=inAndPost(rightInOrder, rightPostOrder);    return root;}}




阅读全文
0 0