leetcode----106. Construct Binary Tree from Inorder and Postorder Traversal

链接:

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

大意:

根据二叉树的中序遍历in和后序遍历post构建二叉树。例子:

思路:

和前一题一样:根据二叉树的先序遍历和中序遍历构造二叉树 只不过是后序遍历序列的最后一个元素才是当前树的根节点值

另:使用前一题改进后的思路

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] in, int[] post) {
        if (in.length == 0)
            return null;
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < in.length; i++) {
            map.put(in[i], i);
        }
        TreeNode root = buildTree(in, 0, in.length - 1, post, 0, post.length - 1, map);
        return root;
    }
    public TreeNode buildTree(int[] in, int s1, int e1, int[] post, int s2, int e2, Map<Integer, Integer> map) {
        if (s1 > e1)
            return null;
        TreeNode root = new TreeNode(post[e2]); // 后序遍历的最后一个节点为根节点
        int s = map.get(post[e2]), count = s - s1;
        root.left = buildTree(in, s1, s - 1, post, s2, s2 + count - 1, map);
        root.right = buildTree(in, s + 1, e1, post, s2 + count, e2 - 1, map);
        return root;
    }
}

结果:

结论:

递归(算法)很美妙 ,有好的数据结构更美妙。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值