刷题笔记02
前序中序,后序中序确定一颗二叉树。
后序中序确定的思路:
从postorder中取出最后一个数
以这个数为分界点分割中序数组
再根据中序的分组分割后序数组
点击查看代码
class Solution {
Map<Integer,Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
for(int i = 0 ; i<inorder.length;i++){
map.put(inorder[i],i);
}
return buildnode(inorder,postorder,0,inorder.length-1,0,inorder.length-1);
}
public TreeNode buildnode(int[] inorder,int[] postorder,int l,int r,int pl,int pr){
if(l>r) return null;
int value = postorder[pr];
TreeNode root = new TreeNode(value);
int idx = map.get(value)-l;
root.left=buildnode(inorder,postorder,l,l+idx-1,pl,pl+idx-1);
root.right=buildnode(inorder,postorder,l+idx+1,r,pl+idx,pr-1);
return root;
}
}
难点在于递归的时候坐标的变化,跟着例子捋一遍就能写出来了。
654最大二叉树
点击查看代码
class Solution {
public TreeNode constructMaximumBinaryTree(int[] nums) {
return coustruct(nums,0,nums.length-1);
}
TreeNode coustruct(int[] nums,int l,int r){
if(l>r) return null;
int max = l;
for(int i = l+1;i<=r;i++){
if(nums[i]>nums[max]){
max = i;
}
}
TreeNode root = new TreeNode(nums[max]);
root.left=coustruct(nums,l,max-1);
root.right=coustruct(nums,max+1,r);
return root;
}
}
递归用最大值分割。时间复杂度为O(n²),最坏情况下为严格递增或递减。递归n蹭,对于第i层每层都要遍历n-i次才能找到最大值。优化点就在于每轮的遍历,如果每次添加元素就完成比较,时间复杂度就可以优化到O(n)。
单调栈:插入元素小于栈中元素,入栈,并把栈中元素的右指针指向入栈元素。大于,出栈直到找到不小于该元素的数,把入栈元素的左指针指向栈中元素。
代码明天写
合并二叉树。
一棵树和两棵树的遍历是一样的,多传一个节点就好了。
递归遍历相加即可,root1==null,return root2。
也可以用队列模拟层序遍历对应位置相加。
,
浙公网安备 33010602011771号