forked from xiaoyaoworm/Leetcode-java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
106_buildTreeFromInPre.java
30 lines (27 loc) · 1.07 KB
/
106_buildTreeFromInPre.java
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
/**
* 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 == null || postorder == null || inorder.length == 0 || postorder.length == 0 || inorder.length!= postorder.length) return null;
int len = inorder.length;
return build(inorder, 0, len-1, postorder, 0, len-1);
}
public TreeNode build(int[] inorder, int in_start, int in_end, int[] postorder, int post_start, int post_end){
if(in_start > in_end || post_start > post_end) return null;
TreeNode root = new TreeNode(postorder[post_end]);
int k = 0;
while(inorder[in_start+k]!= root.val){
k++;
}
root.left = build(inorder, in_start, in_start+k-1, postorder, post_start, post_start+k-1);
root.right = build(inorder, in_start+k+1, in_end, postorder, post_start+k, post_end-1);
return root;
}
}