学习剑指offer: 第19天

76 阅读1分钟

重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。

假设输入的前序遍历和中序遍历的结果中都不含重复的数字。

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
Input: preorder = [-1], inorder = [-1]
Output: [-1]

leetcode-cn.com/problems/zh…

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length ==0){
            return null;
        }

        int rootVal = preorder[0]; 
        int rootIndex = 0;
        for(int i=0;i<preorder.length;i++){
            if(inorder[i] == rootVal){
                rootIndex = i;
                break;
            }
        }
        TreeNode root = new TreeNode(rootVal);
        root.left = buildTree(Arrays.copyOfRange(preorder,1,rootIndex + 1),Arrays.copyOfRange(inorder,0,rootIndex));
        root.right = buildTree(Arrays.copyOfRange(preorder,1+rootIndex,preorder.length),Arrays.copyOfRange(inorder,rootIndex+1,inorder.length));
        return root;
    }
}

数值的整数次方

实现 pow(xn) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。

输入: x = 2.00000, n = 10
输出: 1024.00000
输入: x = 2.10000, n = 3
输出: 9.26100
输入: x = 2.00000, n = -2
输出: 0.25000
解释: 2-2 = 1/22 = 1/4 = 0.25

提示:

  • -100.0 < x < 100.0
  • -231 <= n <= 231-1
  • -104 <= xn <= 104

leetcode-cn.com/problems/sh…

class Solution {
    public double myPow(double x, int n) {
          if(n==0 || x==1.0) return 1.0;
        if(n==1) return x;
        if(n==-1) return 1.0/x;
      
        double res=myPow(x,n/2);
        res = res*res;

        //如果是奇数
        if((n&1)==1 && n>0) res=res*x;   
        if((n&1)==1 && n<0) res=res*1/x; 
        
        return res;
    }
}

二叉搜索树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

输入: [1,6,3,2,5]
输出: false
输入: [1,3,2,6,5]
输出: true

leetcode-cn.com/problems/er…

class Solution {
    public boolean verifyPostorder(int[] postorder) {
        if(postorder.length == 0){
            return true;
        }
        int rootVal = postorder[postorder.length-1];
        int i = postorder.length -2;
        while(i >= 0){
            if(postorder[i] >  rootVal){
                 i--;
            } else {
                break;
            }
        }
        int mid = i;
        while(i >= 0){
            if(postorder[i] < rootVal){
                i--;
            } else {
                break;
            }
        }

        if(i >=0){
            return false;
        }

        return verifyPostorder(Arrays.copyOfRange(postorder, 0, mid+1)) 
        && verifyPostorder(Arrays.copyOfRange(postorder, mid+1, postorder.length-1));
    }
}