题解 | #从中序和后序遍历构造二叉树#

从中序和后序遍历构造二叉树

http://www.nowcoder.com/practice/b0d07d0edc7f495696aecd265d5ef1b9

Arrays.copyOfRange()谁用了不说一句好

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    public TreeNode buildTree (int[] inorder, int[] postorder) {
        // write code here
        if(inorder.length==0||postorder.length==0)
            return null;

        if(inorder.length==1 || postorder.length==1)
            return new TreeNode(inorder[0]);

        int val = postorder[postorder.length-1];

        int mid = 0;
        for(int i = 0 ; i < inorder.length; i ++)
            if(inorder[i]==val)
                mid = i;

        TreeNode root = new TreeNode(val);
        root.left = buildTree(Arrays.copyOfRange(inorder,0,mid),Arrays.copyOfRange(postorder,0,mid));
        root.right = buildTree(Arrays.copyOfRange(inorder,mid+1,inorder.length),Arrays.copyOfRange(postorder,mid,postorder.length-1));
        return root;
    }
}
全部评论

相关推荐

爱看电影的杨桃allin春招:我感觉你在炫耀
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务