剑指 Offer 16. 数值的整数次方 剑指 Offer 36. 二叉搜索树与双向链表

剑指 Offer 16. 数值的整数次方

1、题目

实现 pow(x, n) ,即计算 x 的 n 次幂函数(即,xn)。不得使用库函数,同时不需要考虑大数问题。
在这里插入图片描述

2、题解

算法流程:

  1. 当 x = 0 时:直接返回 0 (避免后续 x = 1 / x 操作报错)。
  2. 初始化 res = 1 ;
  3. 当 n < 0 时:把问题转化至 n ≥ 0 的范围内,即执行 x = 1 / x ,n = - n ;
  4. 循环计算:当 n = 0 时跳出;
    1. 当 n & 1 = 1n&1=1 时:将当前 xx 乘入 resres (即 res *= xres∗=x );
    2. 执行 x = x^2 (即 x *= x );
    3. 执行 nn 右移一位(即 n >>= 1)。
  5. 返回 res 。

3、代码

class Solution {
    public double myPow(double x, int n) {
        if(x == 0) return 0;
        long tmpN = n;
        double res = 1.0;
        if(tmpN < 0) {
            x = 1 / x;
            tmpN = -tmpN;
        }
        while(tmpN > 0) {
            if((tmpN & 1) == 1) res *= x;  //为奇数的情况
            x *= x;
            tmpN >>= 1; //除 2 操作
        }
        return res;
    }
}

剑指 Offer 36. 二叉搜索树与双向链表

1、题目

输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的循环双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
在这里插入图片描述

2、题解

二叉搜索树的中序遍历为 递增序列

  • 排序链表: 节点应从小到大排序,因此应使用 中序遍历 “从小到大”访问树的节点。
  • 双向链表: 在构建相邻节点的引用关系时,设链表最后一个节点 lastNode 和当前节点 currentNode,不仅应构建 lastNode.right = currentNode,也应构建 currentNode.left = lastNode 。
  • 循环链表: 设链表头节点 head 和尾节点 tail ,则应构建 head.left = tail 和 tail.right = head 。

算法流程:
dfs(cur): 递归法中序遍历;

  1. 终止条件: 当节点 currentNode 为空,代表越过叶节点,直接返回;
  2. 递归左子树,即 treeInorder(currentNode.left)
  3. 构建链表
    1. pre 为空时: 代表正在访问链表头节点,记为 head
    2. pre 不为空时: 修改双向节点引用,即 lastNode.right = currentNodecurrentNode.left = lastNode;
    3. 保存 cur : 更新 pre = currentNode,即节点 currentNode 是后继节点的 lastNode
  4. 递归右子树,即 treeInorder(currentNode.right)

3、代码

class Solution {
    Node lastNode = null, head = null;
    public Node treeToDoublyList(Node root) {
        if(root == null) return null;
        treeInorder(root);
        head.left = lastNode;
        lastNode.right = head;
        return head;
        
    }

    public void treeInorder(Node currentNode){
        if(currentNode == null) return;
        treeInorder(currentNode.left);
        if(lastNode != null) lastNode.right = currentNode;
        else head = currentNode;
        currentNode.left = lastNode;
        lastNode = currentNode;
        treeInorder(currentNode.right);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值