【一次过】Lintcode 72. 中序遍历和后序遍历树构造二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/82468968

根据中序遍历和后序遍历树构造二叉树

样例

给出树的中序遍历: [1,2,3] 和后序遍历: [1,3,2]

返回如下的树:

  2

 /  \

1    3

注意事项

你可以假设树中不存在相同数值的节点


解题思路:

类似于Lintcode 73. 前序遍历和中序遍历树构造二叉树,直接看代码

/**
 * 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
        Map<Integer,Integer> map= new HashMap<>();//key为inorder数组中的值,value为对应的数组索引
        for(int i=0 ; i<inorder.length ; i++)
            map.put(inorder[i],i);
        
        return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1,map);
    }
    
    public TreeNode buildTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd,Map<Integer,Integer> map){
        if(inStart>inEnd || postStart>postEnd)
            return null;
        
        int rootVal = postorder[postEnd];
        int rootIndex = map.get(rootVal);
        
        int len = rootIndex - inStart;
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(inorder,inStart,rootIndex-1,postorder,postStart,postStart+len-1,map);
        root.right = buildTree(inorder,rootIndex+1,inEnd,postorder,postStart+len,postEnd-1,map);
        
        return root;
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/82468968