解法大部分源于Krahets的题解
T1 07. 重建二叉树
- 前序 根左右; 中序 左根右; 后序 左右根
测试用例
前序 [3, 9, 20,15,7] 中序 [9 , 3 , 15,20,7]
[根|左| 右 ] [左|根| 右 ]
class Solution {
int[] preorder; //先序数组便于
HashMap<Integer,Integer> dic = new HashMap<Integer,Integer>(); //中序数组
public TreeNode buildTree(int[] preorder, int[] inorder) {
this.preorder = preorder;//先序数组赋值
for(int i=0;i<inorder.length;i++){
dic.put(inorder[i],i); //键:节点 值:坐标
}
return recur(0,0,inorder.length-1);
}
TreeNode recur(int root,int left,int right){
左边界 大于 右边界 递归终止
if(left > right) return null;
//获取此次的根节点
TreeNode node = new TreeNode(preorder[root]);
//获取中序中此次根节点的坐标
int i = dic.get(node.val);
//root+1:前序[1]是左子树的根节点
//left:中序[0]是左子树的开始
//i-1:中序[根-1] 是左子树的结束
node.left = recur(root+1,left,i-1);
//root+i-left+1: 前序[根+左子树长度+1]是右子树的根
//i+1 :中序[根节点+1]是右子树的左边解
//right: 不论前序后序 右子树的右边界是数组的最后一位
node.right = recur(root+i-left+1,i+1,right);
return node;
}
}
T2 16. 数值的整数次方
快速幂
class Solution {
public double myPow(double x, int n) {
if(x==0) return x; // 特例
long b = n; //指数
double res=1.0;
if(b<0){ //指数小于0
b = -b;
x = 1/x; //底数变分数
}
while(b>0){
// b和1进行与运算
if((b&1) == 1) res *= x; //奇数
x *= x; //偶数
b >>=1 ; // 右移一位相当于÷2
}
return res;
}
}
T3 33. 二叉搜索树的后序遍历序列
class Solution {
public boolean verifyPostorder(int[] postorder) {
return recur(postorder,0,postorder.length-1);
}
public boolean recur(int[] postorder,int left,int root){
if(left>root) return true;
//后序是左右根 二叉搜索树左子树小于根,右子树大于在根
//获得左子树的右边界
int tree_left = left;
while(postorder[tree_left]<postorder[root]) tree_left++;
//获取右子树的右边界
int tree_right = tree_left;
while(postorder[tree_right]>postorder[root]) tree_right++;
//右子树右边界+1是根 && 左子树是二叉搜索树 && 右子树是二叉搜索树
return tree_right==root && recur(postorder,left,tree_left-1) && recur(postorder,tree_left,tree_right-1);
}
}