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

从中序与后序遍历序列构造二叉树

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

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 *   public TreeNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param inorder int整型一维数组 中序遍历序列
     * @param postorder int整型一维数组 后序遍历序列
     * @return TreeNode类
     */
    public TreeNode buildTree (int[] inorder, int[] postorder) {
        // write code here
        int n = inorder.length;
        TreeNode root = buildTree(inorder,postorder,0,n-1,0,n-1);
        //1.postorder的末端值为根节点,利用该值在中序数组中找到根节点的位置rootIndex
        //2.以rootIndex为界,inorder数组中instart至rootIndex-1是左子树,rootIndex+1至inend是右子树。
        //2.以postStart+(rootIndex-inStart)为界,postorder数组中poststart至postStart+(rootIndex-inStart)-1是左子树,postStart+(rootIndex-inStart)至end-1是右子树
        return root;
    }
    public TreeNode buildTree(int[] inorder, int[] postorder,int inStart, int inEnd, int postStart, int postEnd){
        int rootIndex = inStart;
        TreeNode root = new TreeNode(postorder[postEnd]);
        for(int i = inStart; i <= inEnd; i++){
            if(inorder[i] == postorder[postEnd]){
                rootIndex = i;
                break;
            }
        }
        int offset = rootIndex-inStart;
        if(inStart<rootIndex){
            //说明有左子树
            root.left = buildTree(inorder,postorder,inStart,rootIndex-1,postStart,postStart+offset-1);
        }
        if(rootIndex<inEnd){
            //说明有右子树
            root.right = buildTree(inorder,postorder,rootIndex+1,inEnd,postStart+offset,postEnd-1);
        }
        return root;
    }
}

全部评论

相关推荐

点赞 评论 收藏
分享
05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务