首页 > 其他分享 >代码随想录训练营|Day 21|530,501,236

代码随想录训练营|Day 21|530,501,236

时间:2022-10-11 04:22:06浏览次数:86  
标签:right return 21 随想录 TreeNode null root Day left

530. Minimum Absolute Difference in BST

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

Example 1:

https://assets.leetcode.com/uploads/2021/02/05/bst1.jpg

Input: root = [4,2,6,1,3]
Output: 1

Example 2:

https://assets.leetcode.com/uploads/2021/02/05/bst2.jpg

Input: root = [1,0,48,null,null,12,49]
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [2, 104].
  • 0 <= Node.val <= 105

最直观的想法,就是把二叉搜索树转换成有序数组,然后遍历一遍数组,就统计出来最小差值了。

class Solution {
    TreeNode pre;// 记录上一个遍历的结点
    int result = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
       if(root == null)return 0;
       traversal(root);
       return result;
    }
    public void traversal(TreeNode root){
        if(root == null)return;
        //左
        traversal(root.left);
        //中
        if(pre != null){
            result = Math.min(result,root.val - pre.val);
        }
        pre = root;
        //右
        traversal(root.right);
    }
}

For Future References

题目链接:https://leetcode.com/problems/minimum-absolute-difference-in-bst/

文章讲解:https://programmercarl.com/0530.二叉搜索树的最小绝对差.html


501. Find Mode in Binary Search Tree

Given the root of a binary search tree (BST) with duplicates, return all the mode(s) (i.e., the most frequently occurred element) in it.

If the tree has more than one mode, return them in any order.

Assume a BST is defined as follows:

  • The left subtree of a node contains only nodes with keys less than or equal to the node's key.
  • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
  • Both the left and right subtrees must also be binary search trees.

Example 1:

https://assets.leetcode.com/uploads/2021/03/11/mode-tree.jpg

Input: root = [1,null,2,2]
Output: [2]

Example 2:

Input: root = [0]
Output: [0]

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • 105 <= Node.val <= 105

Follow up:

Could you do that without using any extra space? (Assume that the implicit stack space incurred due to recursion does not count).

搜索树,它中序遍历就是有序的。
弄一个指针指向前一个节点,这样每次cur(当前节点)才能和pre(前一个节点)作比较。

而且初始化的时候pre = NULL,这样当pre为NULL时候,我们就知道这是比较的第一个元素。

class Solution {
    ArrayList<Integer> resList;
    int maxCount;
    int count;
    TreeNode pre;

    public int[] findMode(TreeNode root) {
        resList = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        findMode1(root);
        int[] res = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            res[i] = resList.get(i);
        }
        return res;
    }

    public void findMode1(TreeNode root) {
        if (root == null) {
            return;
        }
        findMode1(root.left);

        int rootValue = root.val;
        // 计数
        if (pre == null || rootValue != pre.val) {
            count = 1;
        } else {
            count++;
        }
        // 更新结果以及maxCount
        if (count > maxCount) {
            resList.clear();
            resList.add(rootValue);
            maxCount = count;
        } else if (count == maxCount) {
            resList.add(rootValue);
        }
        pre = root;

        findMode1(root.right);
    }
}

For Future References

题目链接:https://leetcode.com/problems/find-mode-in-binary-search-tree/

文章讲解:https://programmercarl.com/0501.二叉搜索树中的众数.html


236. Lowest Common Ancestor of a Binary Tree

Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:

https://assets.leetcode.com/uploads/2018/12/14/binarytree.png

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

https://assets.leetcode.com/uploads/2018/12/14/binarytree.png

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • 109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the tree.

如果left 和 right都不为空,说明此时root就是最近公共节点
如果left为空,right不为空,就返回right,说明目标节点是通过right返回的,反之依然。
如果left和right都为空,则返回left或者right都是可以的,也就是返回空。

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || root == p || root == q) { // 递归结束条件
            return root;
        }

        // 后序遍历
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if(left == null && right == null) { // 若未找到节点 p 或 q
            return null;
        }else if(left == null && right != null) { // 若找到一个节点
            return right;
        }else if(left != null && right == null) { // 若找到一个节点
            return left;
        }else { // 若找到两个节点
            return root;
        }
    }
}

For Future References

题目链接:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/

文章讲解:https://programmercarl.com/0236.二叉树的最近公共祖先.html

标签:right,return,21,随想录,TreeNode,null,root,Day,left
From: https://www.cnblogs.com/bluesociety/p/16777962.html

相关文章

  • 代码随想录训练营|Day 20|654,617,700,98
    654.MaximumBinaryTreeYouaregivenanintegerarray nums withnoduplicates.A maximumbinarytree canbebuiltrecursivelyfrom nums usingthefollo......
  • 实验4:开源控制器实践——OpenDayligh
    一、实验目的能够独立完成OpenDaylight控制器的安装配置;能够使用Postman工具调用OpenDaylightAPI接口下发流表。二、实验环境Ubuntu20.04Desktopamd64三、实验......
  • Day 3: Spiral Memory
    https://adventofcode.com/2017/day/3---Day3:SpiralMemory---Youcomeacrossanexperimentalnewkindofmemorystoredonan infinitetwo-dimensionalgrid......
  • 实验4:开源控制器实践——OpenDaylight
    实验4:开源控制器实践——OpenDaylight一、实验目的1.能够独立完成OpenDaylight控制器的安装配置;2.能够使用Postman工具调用OpenDaylightAPI接口下发流表。二、实验环......
  • 学习python-Day70
    今天学习内容一、自定义频率类fromrest_framework.throttlingimportBaseThrottleclassMyThrottle(BaseThrottle):VISIT_RECORD={}#存放用户访问记录{ip......
  • navisworks2021保姆级下载安装教程
     navisworks2021WIN1064位安装步骤:1.先使用“百度网盘客户端”下载NV_CN_2021软件安装包到电脑磁盘里,并解压缩,安装前先断网,然后找到Autodesk_Navisworks_Manage_2021_......
  • Day03-java学习记录
    类型转换由于Java是强类型语言,所以某些运算,需要用到类型转换!低》》》》》》》》》》》》》》》》》高byte,short,char->int->long->float->double强制转换高到低自......
  • day07 方法重写&super、this、static关键字&JVM的类加载顺序题目
    day07方法重写1)重写发生在子父类当中2)方法名、参数列表、返回值均相同3)重写的方法,方法体或者访问控制修饰符不同4)子类方法的访问权限不能缩小,比如父类是int,子类重写权......
  • day20 700,617,98, 645
    700.二叉搜索树中的搜索classSolution{publicTreeNodesearchBST(TreeNoderoot,intval){if(root.val==val||root==null)returnroot;//1:终止......
  • 代码随想录day20 | 654. 最大二叉树 617. 合并二叉树 700. 二叉搜索树中的搜索 98. 验
    654.最大二叉树题目|文章方法:模拟思路按照题目要求顺序使用递归函数traversal(nums,begin,end)对数组nums二叉树进行模拟。这道题的思路方法与105.从前序遍历和中序......