leetcode--ConstructBinaryTreefromInorderandPostorderTraversal

本文介绍了一种通过后序遍历和中序遍历构建二叉树的方法。利用哈希映射提高节点查找效率,实现从后往前构建二叉树的过程。文章包含完整的Java代码实现。

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

思路:后序遍历前面的节点一定是后面的节点的子节点,因此从后往前遍历可以从根节点向下构造出二叉树。中序遍历左子节点一定在根节点的左边,而右子节点一定在根节点的右边。因此可以通过中序遍历来判断当前节点在树中的位置。

import java.util.HashMap;

/**
 * Created by marsares on 15/6/15.
 */
public class ConstructBinaryTreefromInorderandPostorderTraversal {
    HashMap<Integer,Integer>hm=new HashMap<Integer,Integer>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(postorder.length==0)return null;
        if(postorder.length==1)return new TreeNode(postorder[0]);
        for(int i=0;i<inorder.length;i++){
            hm.put(inorder[i],i);
        }
        TreeNode root=new TreeNode(postorder[postorder.length-1]);
        for(int i=postorder.length-2;i>=0;i--){
            root=traversal(postorder[i],root);
        }
        return root;
    }
    public TreeNode traversal(int val,TreeNode root){
        if(root==null)return new TreeNode(val);
        else if(hm.get(val)>hm.get(root.val))root.right=traversal(val,root.right);
        else root.left=traversal(val,root.left);
        return root;
    }
    public static void main(String[]args){
        ConstructBinaryTreefromInorderandPostorderTraversal cbt=new ConstructBinaryTreefromInorderandPostorderTraversal();
        BinaryTreeSerialize bts=new BinaryTreeSerialize();
        int[]inorder={4,2,5,1,6,3};
        int[]postorder={4,5,2,6,3,1};
        TreeNode root=cbt.buildTree(inorder,postorder);
        System.out.println(bts.Serialize(root));
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值