106. Construct Binary Tree from Inorder and Postorder Traversal
来源:互联网 发布:英文翻译什么软件好 编辑:程序博客网 时间:2024/06/07 11:30
Given inorder and postorder traversal of a tree, construct the binary tree.
这道题与其前一道题的思路是近似的,不同的是对于后序数组我们需要从后向前操作,这其中我们可以利用一个HashMap进行查找时间上的加速,代码如下:
public TreeNode buildTree(int[] inorder, int[] postorder) {
// 特殊情况处理
if(inorder == null || inorder.length == 0 || postorder.length == 0 || postorder == null || inorder.length != postorder.length){
return null;
}
Map<Integer, Integer> hashMap = new HashMap<Integer, Integer>();
for(int i = 0; i < inorder.length; i++){
hashMap.put(inorder[i], i);
}
return buildResultTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1, hashMap);
}
private TreeNode buildResultTree(int[] inorder, int inoLeft, int inoRight, int[] postorder, int posLeft, int posRight, Map<Integer, Integer> hashMap){
if(posLeft > posRight){
return null;
}
TreeNode treeNode = new TreeNode(postorder[posRight]);
int index = hashMap.get(postorder[posRight]);
treeNode.left = buildResultTree(inorder, inoLeft, index - 1, postorder, posLeft, posRight - (inoRight - index) - 1, hashMap);
treeNode.right = buildResultTree(inorder, index + 1, inoRight, postorder, posRight - (inoRight - index), posRight - 1, hashMap);
return treeNode;
}
- LeetCode 106. Construct Binary Tree from Inorder and Postorder Traversal
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode --- 106. Construct Binary Tree from Inorder and Postorder Traversal
- [LeetCode]*106.Construct Binary Tree from Inorder and Postorder Traversal
- [leetcode] 106.Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode#106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Leetcode 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode *** 106. Construct Binary Tree from Inorder and Postorder Traversal
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- Android API Guide for Media and Camera(一)—— 媒体与相机(媒体播放器)
- Ubuntu下mysql常用操作
- atom添加背景颜色
- 100. Same Tree
- 指针和数组
- 106. Construct Binary Tree from Inorder and Postorder Traversal
- AWS坑
- Spring注解
- jstl标签库
- 定时器技术选型の不同业务背景(二)
- Hello World!
- 怎么标识一个dao
- GUI的终极选择--tkinter
- 知乎牛人javaee学习路线