Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 67ac8c7

Browse files
committed
solve 106.从中序与后序遍历序列构造二叉树
1 parent 0b2252d commit 67ac8c7

File tree

1 file changed

+78
-0
lines changed

1 file changed

+78
-0
lines changed
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
/*
2+
* @lc app=leetcode.cn id=106 lang=java
3+
*
4+
* [106] 从中序与后序遍历序列构造二叉树
5+
*
6+
* https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/
7+
*
8+
* algorithms
9+
* Medium (68.64%)
10+
* Likes: 230
11+
* Dislikes: 0
12+
* Total Accepted: 39.9K
13+
* Total Submissions: 58K
14+
* Testcase Example: '[9,3,15,20,7]\n[9,15,7,20,3]'
15+
*
16+
* 根据一棵树的中序遍历与后序遍历构造二叉树。
17+
*
18+
* 注意:
19+
* 你可以假设树中没有重复的元素。
20+
*
21+
* 例如,给出
22+
*
23+
* 中序遍历 inorder = [9,3,15,20,7]
24+
* 后序遍历 postorder = [9,15,7,20,3]
25+
*
26+
* 返回如下的二叉树:
27+
*
28+
* ⁠ 3
29+
* ⁠ / \
30+
* ⁠ 9 20
31+
* ⁠ / \
32+
* ⁠ 15 7
33+
*
34+
*
35+
*/
36+
37+
// @lc code=start
38+
/**
39+
* Definition for a binary tree node.
40+
* public class TreeNode {
41+
* int val;
42+
* TreeNode left;
43+
* TreeNode right;
44+
* TreeNode(int x) { val = x; }
45+
* }
46+
*/
47+
class Solution {
48+
private Map<Integer, Integer> map = new HashMap<>();
49+
50+
public TreeNode buildTree(int[] inorder, int[] postorder) {
51+
if (inorder == null || postorder == null || inorder.length != postorder.length) {
52+
return null;
53+
}
54+
55+
for (int i = 0; i < inorder.length; i++) {
56+
map.put(inorder[i], i);
57+
}
58+
59+
return helper(postorder, postorder.length - 1, 0, inorder.length - 1);
60+
}
61+
62+
private TreeNode helper(int[] postorder, int postIndex, int inStart, int inEnd) {
63+
if (postIndex < 0 || inStart > inEnd) {
64+
return null;
65+
}
66+
67+
TreeNode root = new TreeNode(postorder[postIndex]);
68+
int inIndex = map.get(postorder[postIndex]);
69+
int rightTreeSize = inEnd - inIndex;
70+
71+
root.left = helper(postorder, postIndex - rightTreeSize - 1, inStart, inIndex - 1);
72+
root.right = helper(postorder, postIndex - 1, inIndex + 1, inEnd);
73+
74+
return root;
75+
}
76+
}
77+
// @lc code=end
78+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /