剑指 Offer 07. 重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
题解
/**
* 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;
TreeNode node = new TreeNode(preorder[0]);
int idx = 0;
while(idx < inorder.length && preorder[0] != inorder[idx]) idx++;
node.left = buildTree(Arrays.copyOfRange(preorder, 1, idx + 1), Arrays.copyOfRange(inorder, 0, idx));
node.right = buildTree(Arrays.copyOfRange(preorder, idx + 1, preorder.length), Arrays.copyOfRange(inorder, idx + 1, inorder.length));
return node;
}
}
剑指 Offer 16. 数值的整数次方
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
题解
快速幂法
相当于将幂看作二进制数
class Solution {
public double myPow(double x, int n) {
if(x == 0) return 0;
long b = n;
double res = 1.0;
if(b < 0){
x = 1 / x;
b = -b; // 把b转为正数
}
while(b > 0){
if((b & 1) == 1) res *= x; // 该幂位将x乘入res
x *= x; // x = x^2
b >>= 1; // b右移一位
}
return res;
}
}
剑指 Offer 33. 二叉搜索树的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。
题解
class Solution {
public boolean verifyPostorder(int[] postorder) {
if(postorder.length == 0) return true;
int n = postorder.length;
int root = postorder[n - 1];
int idx = 0;
while(idx < n - 1 && postorder[idx] < root) idx++; // 找到左子树和右子树的分界点
int j = idx;
while(j < n - 1){
if(postorder[j] < root) return false; // 右子树中存在小于root的结点值
j++;
}
return verifyPostorder(Arrays.copyOfRange(postorder, 0, idx)) && verifyPostorder(Arrays.copyOfRange(postorder, idx, n - 1));
}
}
不需要额外空间,使用 i,j 标记当前数组的范围。
class Solution {
public boolean verifyPostorder(int[] postorder) {
return recur(postorder, 0, postorder.length - 1);
}
boolean recur(int[] postorder, int i, int j) {
if(i >= j) return true;
int p = i;
while(postorder[p] < postorder[j]) p++;
int m = p;
while(postorder[p] > postorder[j]) p++;
return p == j && recur(postorder, i, m - 1) && recur(postorder, m, j - 1);
}
}
版权声明:本文为weixin_41317766原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。