剑指Offer第二十天
分治算法(中等)
题1:重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
/**
* 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) {
int length = preorder.length;
int index = 0;
if(length == 0){
return null;
}
//通过前序遍历确定root节点
int rootVal = preorder[0];
//通过中序遍历进行分治,root左元素都在左子树,右元素都在右子树
for(int i = 0; i < length; i++){
if(inorder[i] == rootVal){
index = i;
break;
}
}
TreeNode root = new TreeNode(rootVal);
root.left = buildTree(Arrays.copyOfRange(preorder, 1, 1 + index), Arrays.copyOfRange(inorder, 0, index));
root.right = buildTree(Arrays.copyOfRange(preorder, 1 + index, length), Arrays.copyOfRange(inorder,index+1, length));
return root;
}
}
题2:数值的整数次方
实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
class Solution {
double sum = 1.0;
//快速幂做法
public double myPow(double x, int n) {
if(n==0){
return 1;
}
long l = n;
//对倒数进行处理
if(l < 0){
x = 1/x;
//统一l为正数,就不用分类讨论了
l = -l;
}
while(l > 0){
if((l & 1)==1){
sum *= x;
}
x *= x;
l >>= 1;
}
return sum;
}
}
题3:二叉搜索树的后序遍历序列
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回
true
,否则返回false
。假设输入的数组的任意两个数字都互不相同。
class Solution {
public boolean verifyPostorder(int[] postorder) {
return helper(postorder,0, postorder.length-1);
}
private boolean helper(int[] postorder, int left, int right){
if(left >= right){
return true;
}
int tmp = left;
while(postorder[left]<postorder[right]){
left++;
}
int mid = left;
while(postorder[left]>postorder[right]){
left++;
}
return left == right && helper(postorder, tmp, mid-1) && helper(postorder, mid, right-1);
}
}