
方法1: recursion。和105题一模一样,时间复杂n,空间复杂logn。这边我建议复盘的时候105,106题都去看一下lc官方的解答,虽然我觉得和我思路是一样的,但是我没看lc解答,而且我的算法耗时非常长,所以我建议看一下lc解答,看看他是不是在我的基础上有了优化。
/**
* 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) {
if(inorder.length == 0) return null;
if(inorder.length == 1) return new TreeNode(inorder[0]);
TreeNode root = new TreeNode(postorder[postorder.length-1]);
int rootIndex = 0;
for(int i = 0; i < inorder.length; i++){
if(inorder[i] == postorder[postorder.length-1])
rootIndex = i;
}
root.left = buildTree(Arrays.copyOfRange(inorder,0,rootIndex), Arrays.copyOfRange(postorder,0,rootIndex));
root.right = buildTree(Arrays.copyOfRange(inorder,rootIndex+1,inorder.length), Arrays.copyOfRange(postorder,rootIndex,postorder.length-1));
return root;
}
}
总结:
- 无
博客介绍了一种递归方法,称其与105题解法相同,时间复杂度为n,空间复杂度为logn。建议复盘时查看105、106题LC官方解答,因博主算法耗时较长,推测官方解答可能有优化。
334

被折叠的 条评论
为什么被折叠?



