ð 106. ä»äžåºäžååºéååºåæé äºåæ
2022幎10æ10æ¥
- algorithm
ð 106. ä»äžåºäžååºéååºåæé äºåæ
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
// æè·¯ïŒ
// æ ¹æ®ååºéåçæ ¹èç¹æŸå°äžåºéå对åºäœçœ®
int len = inorder.length;
return mySol(inorder, postorder, 0, len - 1, 0, len - 1);
}
private TreeNode mySol(int[] inorder, int[] postorder, int inl, int inr, int pl, int pr) {
// éåœç»æ¢æ¡ä»¶
if(inl > inr) {
return null;
}
int val = postorder[pr];
TreeNode root = new TreeNode(val);
if(inl == inr) {
return root;
}
// inl < inr
int index = inl;
while(index <= inr) {
if(inorder[index] == val) {
break;
} else {
index ++;
}
}
root.left = mySol(inorder, postorder, inl, index - 1, pl, index + pl - inl - 1);
root.right = mySol(inorder, postorder, index + 1, inr, index + pl - inl, pr - 1);
return root;
}
}