算法修炼Day21|530.二叉搜索树的最小绝对差 ● 501.二叉搜索树中的众数 ● 236. 二叉树的最近公共祖先

48 阅读1分钟
题目:530. 二叉搜索树的最小绝对差 - 力扣(LeetCode)
思路/想法:

两个数之间差值最小的值一定是在相邻节点之间的值中,采用中序遍历,双指针控制

代码实现:
class Solution {
    TreeNode pre;
    int ans = Integer.MAX_VALUE;
    public int getMinimumDifference(TreeNode root) {
        if (root == null) return 0;
        traversal(root);
        return ans;
    }
    private void traversal(TreeNode root) {
        if (root == null) return;
        traversal(root.left);
        if (pre != null) {
            ans = Math.min(ans, root.val - pre.val);
        }
        pre = root;
        traversal(root.right);
    }
}
题目:501. 二叉搜索树中的众数 - 力扣(LeetCode)
思路/想法:

二叉搜索树中的众数,中序遍历,如果相同于前一个数值则进行++,否则进行比较输出结果。

代码实现:
class Solution {
    ArrayList<Integer> ans;
    int maxCount;
    int count;
    TreeNode pre;
    public int[] findMode(TreeNode root) {
        ans = new ArrayList<>();
        maxCount = 0;
        count = 0;
        pre = null;
        findMode1(root);
        int[] res = new int[ans.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = ans.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++;
        }
        if (count > maxCount) {
            ans.clear();
            ans.add(rootValue);
            maxCount = count;
        } else if (count == maxCount) {
            ans.add(rootValue);
        }
        pre = root;
        findMode1(root.right);
    }
}
题目:leetcode.cn/problems/lo…
思路/想法:

后续遍历

代码实现:
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;
        }
    }
}