当前位置: 首页 > article >正文

LC刷题专题:二叉树;迭代;递归(897、1372、208)

文章目录

  • 897.递增顺序搜索树
  • 1372. 二叉树中的最长交错路径
  • 208. 实现 Trie (前缀树)

897.递增顺序搜索树

https://leetcode.cn/problems/increasing-order-search-tree/description/
在这里插入图片描述
这道题目本身就是一个简单题:非常容易实现:只需要在递归或者迭代中序遍历的同时保存一个临时节点,随后每遍历到一个节点,就把当前节点放到临时节点的右边,同时将临时节点更改为当前遍历到的节点。
迭代版本:

class Solution {
    TreeNode ans = new TreeNode();
    public TreeNode increasingBST(TreeNode root) {
        TreeNode res = ans;
        Deque<TreeNode> dq = new ArrayDeque<>();
        if(root == null){
            return ans;
        }
        TreeNode cur = root;
        while(!dq.isEmpty() || cur != null){
            if(cur != null){
                dq.addLast(cur);
                cur = cur.left;
            }else{
                cur = dq.pollLast();
                TreeNode temp = cur.right;
                cur.left = null;
                ans.right = cur;
                ans = cur;
                cur = temp;
            }
        }
        return res.right;
    }
}

递归版本:

class Solution {
    TreeNode ans = new TreeNode();
    public TreeNode increasingBST(TreeNode root) {
        TreeNode res = ans;
        buildIncrementTree(root);
        return res.right;
    }
    public void buildIncrementTree(TreeNode root){
        if(root == null){
            return;
        }
        buildIncrementTree(root.left);
        TreeNode cur = new TreeNode(root.val);
        ans.right = cur;
        ans = cur;
        buildIncrementTree(root.right);
    }
}

1372. 二叉树中的最长交错路径

参考我之前写过的一篇博客:
https://blog.csdn.net/weixin_45863010/article/details/139708882

208. 实现 Trie (前缀树)

参考之前文章:
https://blog.csdn.net/weixin_45863010/article/details/136297891


http://www.kler.cn/news/332793.html

相关文章:

  • 超详细讲解:DP和DDP的区别以及使用方法
  • dubbo微服务
  • 国创——基于分离表示的人脸图像生成技术
  • 9.30学习记录(补)
  • layui动态表格出现 横竖间隔线
  • JavaScript 数组方法
  • 查缺补漏----程序查询,中断,DMA方式(结合设备驱动程序)
  • 理解无监督学习、无监督图像分割
  • 在 commit 里使用 emoji~
  • C语言-c语言组成
  • Redis实现点赞
  • 前端大模型入门:使用Transformers.js手搓纯网页版RAG(二)- qwen1.5-0.5B - 纯前端不调接口
  • 【React】增量传输与渲染
  • 数据结构--绪论
  • 深度学习:基于MindSpore实现CycleGAN壁画修复
  • 国创——VR虚拟陪伴
  • 向PHP传入参数的三种方法
  • React 解释常见的 hooks: useState / useRef / useContext / useReducer
  • 奔驰EQS450suv升级增强AR抬头显示HUD案例分享
  • 【笔记】平面