今天的题好难,都不咋会,再多练练吧
思路:先序遍历的第一个结点是根节点,在中序遍历中找到根节点位置,将其分为左右子树。
再递归寻找左右子树的根节点。
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder.length == 0)
return null;
int rootVal = preorder[0];
int index = 0;
for (int i=0;i<inorder.length;i++){
if (inorder[i] == rootVal){
index = i;
break;
}
}
TreeNode root = new TreeNode(rootVal);
//Arrays.copyOfRange返回一个左闭右开的数组
root.left = buildTree(Arrays.copyOfRange(preorder,1,index+1),Arrays.copyOfRange(inorder,0,index));
root.right = buildTree(Arrays.copyOfRange(preorder,index+1,preorder.length),Arrays.copyOfRange(inorder,index+1,inorder.length));
return root;
}
思路:这题还没有理解透彻,后续再补思路吧
public double myPow(double x, int n) {
if(n == 0) return 1;
if(n == 1) return x;
if(n == -1) return 1 / x;
double half = myPow(x, n / 2);
double mod = myPow(x, n % 2);
return half * half * mod;
}
思路:(搜索二叉树性质:左子树结点均小于根节点;右子树结点均大于根节点)这题也是看大佬的做法,代码注释有。
class Solution {
// 要点:二叉搜索树中根节点的值大于左子树中的任何一个节点的值,小于右子树中任何一个节点的值,子树也是
public boolean verifyPostorder(int[] postorder) {
if (postorder.length < 2) return true;
return verify(postorder, 0, postorder.length - 1);
}
// 递归实现
private boolean verify(int[] postorder, int left, int right){
if (left >= right) return true; // 当前区域不合法的时候直接返回true就好
int rootValue = postorder[right]; // 当前树的根节点的值
int k = left;
while (k < right && postorder[k] < rootValue){ // 从当前区域找到第一个大于根节点的,说明后续区域数值都在右子树中
k++;
}
for (int i = k; i < right; i++){ // 进行判断后续的区域是否所有的值都是大于当前的根节点,如果出现小于的值就直接返回false
if (postorder[i] < rootValue) return false;
}
// 当前树没问题就检查左右子树
if (!verify(postorder, left, k - 1)) return false; // 检查左子树
if (!verify(postorder, k, right - 1)) return false; // 检查右子树
return true; // 最终都没问题就返回true
}
}
文章介绍了如何使用先序遍历和中序遍历来重建二叉树,以及二叉搜索树的后序遍历序列验证方法。同时,探讨了数值的整数次方计算的递归策略。
1233

被折叠的 条评论
为什么被折叠?



