p106

LeetCode p106 Construct Binary Tree from Inorder and Postorder Traversal 题解

1.题目:

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

题意:

输入一二叉树的中序遍历,后续遍历,返回这个二叉树。

2.解题思路:

后续的最后一个为头,切分中序,递归。

3.代码


[title] [] [url] [link text]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
if (inorder.length == 0)
return null;
int len = postorder.length;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();

for (int i = 0; i < len; i++) {
map.put(inorder[i], i);
}

return buildTree(inorder, 0, len - 1, postorder, 0, len - 1, map);
}

public TreeNode buildTree(int[] inorder, int is, int ie,
int[] postorder, int ps, int pe, HashMap<Integer, Integer> map) {
if (is > ie || ps > pe)
return null;
TreeNode node = new TreeNode(postorder[pe]);
//System.out.println(postorder[pe]);
int k = map.get(postorder[pe]);
node.left = buildTree(inorder, is, k - 1, postorder, ps, ps+k-1-is, map);
node.right = buildTree(inorder, k + 1, ie, postorder, ps+k-is, pe-1, map);
return node;
}
}

4.一些总结: