题目链接

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

题目描述

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:

你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
/ \
9 20
/ \
15 7

题解

本题和已知前序遍历和中序遍历构造二叉树一样,递归构造即可。

代码

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder == null || inorder.length == 0) { return null; }
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return buildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
} public TreeNode buildTree(int[] a, int a1, int a2, int[] b, int b1, int b2) {
if (a1 > a2 || b1 > b2) { return null; }
int mid = map.get(b[b2]);
int count = mid - a1;
TreeNode root = new TreeNode(b[b2]);
root.left = buildTree(a, a1, mid - 1, b, b1, b1 + count - 1);
root.right = buildTree(a, mid + 1, a2, b, b1 + count, b2 - 1);
return root;
}
}

最新文章

  1. lua自定义迭代器
  2. RabbitMQ的安装
  3. 使用PDF.JS在线查看PDF
  4. SpringMVC视图机制详解[附带源码分析]
  5. 简单的下拉刷新以及优化--SwipeRefreshLayout
  6. windows下编译支持https的libcurl
  7. mono &amp; apache install
  8. gzip命令
  9. hdu 5410 CRB and His Birthday(混合背包)
  10. SpringMVC+easyui显示数据
  11. Python day02 三元运算
  12. serialPort操作结构体Hashtable的使用
  13. WebGL three.js学习笔记 纹理贴图模拟太阳系运转
  14. pytorch autograd backward函数中 retain_graph参数的作用,简单例子分析,以及create_graph参数的作用
  15. C# 指定程序打开指定文件
  16. 支持向量机(Support Vector Machine,SVM)
  17. android全屏/沉浸式状态栏下,各种键盘挡住输入框解决办法
  18. 【运维】Dell R710如何做Raid0与Raid5
  19. python接口自动化29-requests-html支持JavaScript渲染页面
  20. python--第十四天总结(js)

热门文章

  1. SpringBoot | 第十五章:基于Postman的RESTful接口测试
  2. 【解决】Git failed with a fatal error. Authentication failed for ‘http://......’
  3. BZOJ3624: [Apio2008]免费道路(最小生成树)
  4. Every ending is just a new beginning.
  5. 【Android车载系统 News | Tech 5】车载设计开发
  6. OpenFirewall
  7. 安装windows phone 7
  8. nbtscan ip地址
  9. 获得session中的用户信息
  10. [Asp.Net] MVC 和Web API Action 获取参数的区别