Leetcode: Construct Binary Tree from Inorder and Postorder Traversal

本文介绍了一种通过中序和后序遍历构建二叉树的方法。利用递归思想,找到根节点,并根据中序遍历划分左右子树,进而递归构造整棵树。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

Example:

inorder: DBEFAGC

postorder: DFEBGCA

Root start with the last element of postorder array, A. In inorder array, all elements going before A are left child, and all elements following after A are right child. And the next right root start with C, left root start with B, both of whose position can be inferred from position of A in inorder and postorder array.

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0) {
            return null;
        }
        
        return helperTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
    }
    
    private TreeNode helperTree(int[] inorder, int instart, int inend, int[] postorder, int poststart, int postend) {
        if (instart > inend) {
            return null;
        }
        
        TreeNode root = new TreeNode(postorder[postend]);
        int pos = findPos(inorder, instart, inend, postorder[postend]);
        root.right = helperTree(inorder, pos + 1, inend, postorder, poststart + pos - instart, postend - 1);
        root.left = helperTree(inorder, instart, pos - 1, postorder, poststart, poststart + pos - instart - 1);
        return root;
    }
    
    private int findPos(int[] array, int start, int end, int key) {
        for (int i = start; i <= end; i++) {
            if (array[i] == key) {
                return i;
            }
        }
        
        return -1;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值