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

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值