class037 二叉树高频题目-下-不含树型dp【算法】

简介: class037 二叉树高频题目-下-不含树型dp【算法】

class037 二叉树高频题目-下-不含树型dp【算法】

code1 236. 二叉树的最近公共祖先

// 普通二叉树上寻找两个节点的最近公共祖先

// 测试链接 : https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/

package class037;
// 普通二叉树上寻找两个节点的最近公共祖先
// 测试链接 : https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
public class Code01_LowestCommonAncestor {
  // 不提交这个类
  public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
  }
  // 提交如下的方法
  public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    if (root == null || root == p || root == q) {
      // 遇到空,或者p,或者q,直接返回
      return root;
    }
    TreeNode l = lowestCommonAncestor(root.left, p, q);
    TreeNode r = lowestCommonAncestor(root.right, p, q);
    if (l != null && r != null) {
      // 左树也搜到,右树也搜到,返回root
      return root;
    }
    if (l == null && r == null) {
      // 都没搜到返回空
      return null;
    }
    // l和r一个为空,一个不为空
    // 返回不空的那个
    return l != null ? l : r;
  }
}

code2 235. 二叉搜索树的最近公共祖先

// 搜索二叉树上寻找两个节点的最近公共祖先

// 测试链接 : https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/

package class037;
// 搜索二叉树上寻找两个节点的最近公共祖先
// 测试链接 : https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree/
public class Code02_LowestCommonAncestorBinarySearch {
  // 不提交这个类
  public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
  }
  // 提交如下的方法
  public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
    // root从上到下
    // 如果先遇到了p,说明p是答案
    // 如果先遇到了q,说明q是答案
    // 如果root在p~q的值之间,不用管p和q谁大谁小,只要root在中间,那么此时的root就是答案
    // 如果root在p~q的值的左侧,那么root往右移动
    // 如果root在p~q的值的右侧,那么root往左移动
    while (root.val != p.val && root.val != q.val) {
      if (Math.min(p.val, q.val) < root.val && root.val < Math.max(p.val, q.val)) {
        break;
      }
      root = root.val < Math.min(p.val, q.val) ? root.right : root.left;
    }
    return root;
  }
}

code3 113. 路径总和 II

// 收集累加和等于aim的所有路径

// 测试链接 : https://leetcode.cn/problems/path-sum-ii/

package class037;
import java.util.ArrayList;
import java.util.List;
// 收集累加和等于aim的所有路径
// 测试链接 : https://leetcode.cn/problems/path-sum-ii/
public class Code03_PathSumII {
  // 不提交这个类
  public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
  }
  // 提交如下的方法
  public static List<List<Integer>> pathSum(TreeNode root, int aim) {
    List<List<Integer>> ans = new ArrayList<>();
    if (root != null) {
      List<Integer> path = new ArrayList<>();
      f(root, aim, 0, path, ans);
    }
    return ans;
  }
  public static void f(TreeNode cur, int aim, int sum, List<Integer> path, List<List<Integer>> ans) {
    if (cur.left == null && cur.right == null) {
      // 叶节点
      if (cur.val + sum == aim) {
        path.add(cur.val);
        copy(path, ans);
        path.remove(path.size() - 1);
      }
    } else {
      // 不是叶节点
      path.add(cur.val);
      if (cur.left != null) {
        f(cur.left, aim, sum + cur.val, path, ans);
      }
      if (cur.right != null) {
        f(cur.right, aim, sum + cur.val, path, ans);
      }
      path.remove(path.size() - 1);
    }
  }
  public static void copy(List<Integer> path, List<List<Integer>> ans) {
    List<Integer> copy = new ArrayList<>();
    for (Integer num : path) {
      copy.add(num);
    }
    ans.add(copy);
  }
}

code4 110. 平衡二叉树

// 验证平衡二叉树

// 测试链接 : https://leetcode.cn/problems/balanced-binary-tree/

package class037;
// 验证平衡二叉树
// 测试链接 : https://leetcode.cn/problems/balanced-binary-tree/
public class Code04_BalancedBinaryTree {
  // 不提交这个类
  public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
  }
  // 提交如下的方法
  public static boolean balance;
  public static boolean isBalanced(TreeNode root) {
    // balance是全局变量,所有调用过程共享
    // 所以每次判断开始时,设置为true
    balance = true;
    height(root);
    return balance;
  }
  // 一旦发现不平衡,返回什么高度已经不重要了
  public static int height(TreeNode cur) {
    if (!balance || cur == null) {
      return 0;
    }
    int lh = height(cur.left);
    int rh = height(cur.right);
    if (Math.abs(lh - rh) > 1) {
      balance = false;
    }
    return Math.max(lh, rh) + 1;
  }
}

code5 98. 验证二叉搜索树

// 验证搜索二叉树

// 测试链接 : https://leetcode.cn/problems/validate-binary-search-tree/

code1 中序遍历判断是否升序

code2 递归

package class037;
// 验证搜索二叉树
// 测试链接 : https://leetcode.cn/problems/validate-binary-search-tree/
public class Code05_ValidateBinarySearchTree {
  // 不提交这个类
  public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
  }
  // 提交以下的方法
  public static int MAXN = 10001;
  public static TreeNode[] stack = new TreeNode[MAXN];
  public static int r;
  // 提交时改名为isValidBST
  public static boolean isValidBST1(TreeNode head) {
    if (head == null) {
      return true;
    }
    TreeNode pre = null;
    r = 0;
    while (r > 0 || head != null) {
      if (head != null) {
        stack[r++] = head;
        head = head.left;
      } else {
        head = stack[--r];
        if (pre != null && pre.val >= head.val) {
          return false;
        }
        pre = head;
        head = head.right;
      }
    }
    return true;
  }
  public static long min, max;
  // 提交时改名为isValidBST
  public static boolean isValidBST2(TreeNode head) {
    if (head == null) {
      min = Long.MAX_VALUE;
      max = Long.MIN_VALUE;
      return true;
    }
    boolean lok = isValidBST2(head.left);
    long lmin = min;
    long lmax = max;
    boolean rok = isValidBST2(head.right);
    long rmin = min;
    long rmax = max;
    min = Math.min(Math.min(lmin, rmin), head.val);
    max = Math.max(Math.max(lmax, rmax), head.val);
    return lok && rok && lmax < head.val && head.val < rmin;
  }
}

code6 669. 修剪二叉搜索树

// 修剪搜索二叉树

// 测试链接 : https://leetcode.cn/problems/trim-a-binary-search-tree/

package class037;
// 修剪搜索二叉树
// 测试链接 : https://leetcode.cn/problems/trim-a-binary-search-tree/
public class Code06_TrimBinarySearchTree {
  // 不提交这个类
  public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
  }
  // 提交以下的方法
  // [low, high]
  public static TreeNode trimBST(TreeNode cur, int low, int high) {
    if (cur == null) {
      return null;
    }
    if (cur.val < low) {
      return trimBST(cur.right, low, high);
    }
    if (cur.val > high) {
      return trimBST(cur.left, low, high);
    }
    // cur在范围中
    cur.left = trimBST(cur.left, low, high);
    cur.right = trimBST(cur.right, low, high);
    return cur;
  }
}

code7 337. 打家劫舍 III

// 二叉树打家劫舍问题

// 测试链接 : https://leetcode.cn/problems/house-robber-iii/

package class037;
// 二叉树打家劫舍问题
// 测试链接 : https://leetcode.cn/problems/house-robber-iii/
public class Code07_HouseRobberIII {
  // 不提交这个类
  public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
  }
  // 提交如下的方法
  public static int rob(TreeNode root) {
    f(root);
    return Math.max(yes, no);
  }
  // 全局变量,完成了X子树的遍历,返回之后
  // yes变成,X子树在偷头节点的情况下,最大的收益
  public static int yes;
  // 全局变量,完成了X子树的遍历,返回之后
  // no变成,X子树在不偷头节点的情况下,最大的收益
  public static int no;
  public static void f(TreeNode root) {
    if (root == null) {
      yes = 0;
      no = 0;
    } else {
      int y = root.val;
      int n = 0;
      f(root.left);
      y += no;
      n += Math.max(yes, no);
      f(root.right);
      y += no;
      n += Math.max(yes, no);
      yes = y;
      no = n;
    }
  }
}


相关文章
|
2月前
|
存储 算法
算法入门:专题二---滑动窗口(长度最小的子数组)类型题目攻克!
给定一个正整数数组和目标值target,找出总和大于等于target的最短连续子数组长度。利用滑动窗口(双指针)优化,维护窗口内元素和,通过单调性避免重复枚举,时间复杂度O(n)。当窗口和满足条件时收缩左边界,更新最小长度,最终返回结果。
|
2月前
|
存储 机器学习/深度学习 监控
网络管理监控软件的 C# 区间树性能阈值查询算法
针对网络管理监控软件的高效区间查询需求,本文提出基于区间树的优化方案。传统线性遍历效率低,10万条数据查询超800ms,难以满足实时性要求。区间树以平衡二叉搜索树结构,结合节点最大值剪枝策略,将查询复杂度从O(N)降至O(logN+K),显著提升性能。通过C#实现,支持按指标类型分组建树、增量插入与多维度联合查询,在10万记录下查询耗时仅约2.8ms,内存占用降低35%。测试表明,该方案有效解决高负载场景下的响应延迟问题,助力管理员快速定位异常设备,提升运维效率与系统稳定性。
222 4
|
2月前
|
存储 算法 编译器
算法入门:剑指offer改编题目:查找总价格为目标值的两个商品
给定递增数组和目标值target,找出两数之和等于target的两个数字。利用双指针法,left从头、right从尾向中间逼近,根据和与target的大小关系调整指针,时间复杂度O(n),空间复杂度O(1)。找不到时返回{-1,-1}。
|
5月前
|
监控 算法 安全
基于 C# 基数树算法的网络屏幕监控敏感词检测技术研究
随着数字化办公和网络交互迅猛发展,网络屏幕监控成为信息安全的关键。基数树(Trie Tree)凭借高效的字符串处理能力,在敏感词检测中表现出色。结合C#语言,可构建高时效、高准确率的敏感词识别模块,提升网络安全防护能力。
145 2
|
7月前
|
存储 机器学习/深度学习 算法
KMP、Trie树 、AC自动机‌ ,三大算法实现 优雅 过滤 netty 敏感词
KMP、Trie树 、AC自动机‌ ,三大算法实现 优雅 过滤 netty 敏感词
KMP、Trie树 、AC自动机‌ ,三大算法实现 优雅 过滤 netty  敏感词
|
7月前
|
监控 算法 数据处理
基于 C++ 的 KD 树算法在监控局域网屏幕中的理论剖析与工程实践研究
本文探讨了KD树在局域网屏幕监控中的应用,通过C++实现其构建与查询功能,显著提升多维数据处理效率。KD树作为一种二叉空间划分结构,适用于屏幕图像特征匹配、异常画面检测及数据压缩传输优化等场景。相比传统方法,基于KD树的方案检索效率提升2-3个数量级,但高维数据退化和动态更新等问题仍需进一步研究。未来可通过融合其他数据结构、引入深度学习及开发增量式更新算法等方式优化性能。
197 17
|
7月前
|
存储 监控 算法
局域网上网记录监控的 C# 基数树算法高效检索方案研究
在企业网络管理与信息安全领域,局域网上网记录监控是维护网络安全、规范网络行为的关键举措。随着企业网络数据量呈指数级增长,如何高效存储和检索上网记录数据成为亟待解决的核心问题。基数树(Trie 树)作为一种独特的数据结构,凭借其在字符串处理方面的卓越性能,为局域网上网记录监控提供了创新的解决方案。本文将深入剖析基数树算法的原理,并通过 C# 语言实现的代码示例,阐述其在局域网上网记录监控场景中的具体应用。
179 7
|
6月前
|
机器学习/深度学习 算法 搜索推荐
决策树算法如何读懂你的购物心理?一文看懂背后的科学
"你为什么总能收到刚好符合需求的商品推荐?你有没有好奇过,为什么刚浏览过的商品就出现了折扣通知?
|
9月前
|
人工智能 算法 语音技术
Video-T1:视频生成实时手术刀!清华腾讯「帧树算法」终结闪烁抖动
清华大学与腾讯联合推出的Video-T1技术,通过测试时扩展(TTS)和Tree-of-Frames方法,显著提升视频生成的连贯性与文本匹配度,为影视制作、游戏开发等领域带来突破性解决方案。
320 4
Video-T1:视频生成实时手术刀!清华腾讯「帧树算法」终结闪烁抖动
|
9月前
|
存储 算法 Java
算法系列之数据结构-二叉树
树是一种重要的非线性数据结构,广泛应用于各种算法和应用中。本文介绍了树的基本概念、常见类型(如二叉树、满二叉树、完全二叉树、平衡二叉树、B树等)及其在Java中的实现。通过递归方法实现了二叉树的前序、中序、后序和层次遍历,并展示了具体的代码示例和运行结果。掌握树结构有助于提高编程能力,优化算法设计。
305 10
 算法系列之数据结构-二叉树

热门文章

最新文章