Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal 中序和后序恢复二叉树

来源:互联网 发布:微信运动的数据来源 编辑:程序博客网 时间:2024/05/16 01:14

1 解题思想

这道题和105的思想,基本就是一致的,这里将会说的比较简单,之说下不同
Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 先序和中序中恢复二叉树 解题报告

和之前的那个不同的是,前序向前看,后序则是向后看,后序最后一个一定是根节点,中序中每一段,在后序中最后出现那个,也一定是根节点

btw:
如果没记错的话,前序和后续是不能恢复二叉树的,无论怎么恢复,都必须要现有中序

如果问题,请指教

2 原题

Given inorder and postorder traversal of a tree, construct the binary tree.Note:You may assume that duplicates do not exist in the tree. 

3 AC解

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */  /**  * post:left-right-root  * inorder:left-root-right  * */public class Solution {      /**     * 核心思想     * 同上题,只是需要记得postorder从后面开始,然后改一下位置参数就可以了     * */    public TreeNode buildTreeHelper(int[] inorder,int is,int ie,int[] preorder,int ps) {        if(is>ie || ps < 0) return null;        //首先从inorder中确定第一个,然后既可以划分左右子树        //System.out.println(ps);        TreeNode root = new TreeNode(preorder[ps]);        int rootAtIn = is;        while(inorder[rootAtIn] != root.val) rootAtIn ++;        //拆分成两个子问题        root.left =  buildTreeHelper(inorder,is,rootAtIn - 1,preorder,ps-(ie- rootAtIn + 1));        root.right = buildTreeHelper(inorder,rootAtIn+1,ie,preorder,ps-1);        return root;    }    public TreeNode buildTree(int[] inorder, int[] postorder) {           return buildTreeHelper(inorder,0,inorder.length-1,postorder,postorder.length-1);    }}
0 0