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