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

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

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    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 {
public TreeNode buildTree(int[] inorder, int[] postorder) {
Map<Integer, Integer> mymap = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
mymap.put(inorder[i], i);
}
return helper(0, inorder.length - 1, 0, postorder.length - 1, postorder, mymap);
} private TreeNode helper(int inLeft, int inRight, int postLeft, int postRight, int[] postorder, Map<Integer, Integer> mymap) {
if (inLeft > inRight) {
return null;
}
TreeNode cur = new TreeNode(postorder[postRight]);
int index = mymap.get(postorder[postRight]);
int leftSize = index - inLeft;
// postRight for left just add up leftSize
cur.left = helper(inLeft, index - 1, postLeft, postLeft + leftSize - 1, postorder, mymap);
cur.right = helper(index + 1, inRight, postLeft + leftSize, postRight - 1, postorder, mymap);
return cur;
}
}

最新文章

  1. Consistent hashing —— 一致性哈希
  2. Maven安装与配置
  3. OpenCV人形检测Hog
  4. 《BI项目笔记》历年外观质量均值变化分析Cube的建立
  5. VC++ 在控件上写字时 字体的设置技巧
  6. Java Socket编程readLine返回null,read返回-1的条件
  7. JavaScript的变量提升
  8. 常用的dos命令之简略总结
  9. picturefill + picture 标签 实现兼容性很棒的 响应式图片 自适应 屏幕大小
  10. 18-EasyNetQ:发生错误的情况
  11. nyoj 寻找最大数(二)
  12. Android相关面试题---初识
  13. https://www.cnblogs.com/yudanqu/p/9467803.html
  14. Linux-task_struct和文件系统及管道的关系
  15. 【WebAPI No.5】Core WebAPI中的自定义格式化
  16. nginx 执行理解
  17. python——读取MATLAB数据文件 *.mat
  18. 在ecplise中创建一个maven工程
  19. dmesg命令详解
  20. [POI2015]Trzy wieże

热门文章

  1. POJ 1200 Crazy Search 字符串的Hash查找
  2. 【Python】关于import QtCore报错的处理方法
  3. 吴裕雄--天生自然MySQL学习笔记:MySQL 元数据
  4. SQL基础教程(第2版)第3章 聚合与排序:练习题
  5. AI 领域与概述
  6. STM32重映射
  7. 吴裕雄--天生自然 PHP开发学习:表单 - 验证邮件和URL
  8. PAT Advanced 1023 Have Fun with Numbers (20) [⼤整数运算]
  9. python-day5爬虫基础之正则表达式2
  10. 迅为iTOP-开发板-驱动-can和rfid配置