ð 105. ä»ååºäžäžåºéååºåæé äºåæ
2022幎10æ10æ¥
- algorithm
ð 105. ä»ååºäžäžåºéååºåæé äºåæ
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* 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[] preorder, int[] inorder) {
// æè·¯ïŒ
// æ ¹æ®å
åºéåïŒæŸå°åºéŽçæ ¹èç¹ïŒå¯¹åºäžåºéåçäœçœ®ïŒå·ŠèŸ¹äžºå·Šåæ ïŒå³èŸ¹äžºå³åæ
int len = preorder.length;
return mySol(preorder, inorder, 0, len - 1, 0, len - 1);
}
private TreeNode mySol(int[] preorder, int[] inorder, int pl, int pr, int inl, int inr) {
// éåœç»æ¢æ¡ä»¶
if(pl > pr) {
return null;
}
int val = preorder[pl];
TreeNode root = new TreeNode(val);
if(pl == pr) {
return root;
}
// pl < pr
int index = inl;
while(index <= inr) {
if(inorder[index] == val) {
break;
} else {
index ++;
}
}
// 对 index è¿è¡æå
root.left = mySol(preorder, inorder, pl + 1, index + pl - inl, inl, index - 1);
root.right = mySol(preorder, inorder, index + pl - inl + 1, pr, index + 1, inr);
return root;
}
}