键指offer java day20 分治算法

解法大部分源于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. 数值的整数次方

快速幂

image

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);
    } 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值