代码随想录算法训练营 day 21: 530.二叉搜索树的最小绝对差 | 501.二叉搜索树中的众数 | 236. 二叉树的最近公共祖先

72 阅读2分钟

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:

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

Example 2:

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

中序遍历是二叉搜索树的普遍应用场景。这道题目是在BST里使用双指针。要注意在中序遍历时,前一个元素的位置在哪。由于是排过序的,用当前节点值减去前一节点值即可得到差值,没必须要取绝对值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    TreeNode pre = null;
    int mmin = Integer.MAX_VALUE;
    public void rcHelper(TreeNode root) {
        if(root == null) {
            return;
        }

        rcHelper(root.left);

        if(pre != null) {
            int cur_abs = root.val - pre.val;
            mmin = Math.min(cur_abs, mmin);
        }
        pre = root;
       
        rcHelper(root.right);

    }

    public int getMinimumDifference(TreeNode root) {
        rcHelper(root);

        return mmin;
    }
}

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:

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

找到出现最多次的N个元素。这题不容易想的地方在于一次递归怎么写。 由于BST,相同的元素必定在中序遍历中相邻,所以还是走中序遍历。用一个全局变量存前一节点,在用一个全局数组存结果,然后还要两个全局变量存count和maxCount 只扫一次的话,每次在count超过maxCount的时候,要清掉result数组。逻辑条件要注意。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int mmax_count;
    List<Integer> ans = new ArrayList<Integer>();
    TreeNode pre;
    int count;

    public void rcHelper(TreeNode node) {
        if(node == null) {
            return;
        }

        rcHelper(node.left);
        if(pre == null) {
            //root node
            count=1;
            mmax_count = 1;
            ans.add(node.val);
        }
        else {
        //System.out.println(Integer.toString(node.val) + "," + Integer.toString(pre.val));
        //System.out.println(count);

            if(node.val == pre.val) {
                count++;

            }
            else {
                count = 1;
            }
            if(count > mmax_count) {
                ans.clear();
                mmax_count = count;
                ans.add(node.val);
            }
            else if (count == mmax_count) {
                ans.add(node.val);
            }            
        }
        pre = node;
        rcHelper(node.right);
    }

    public int[] findMode(TreeNode root) {
        rcHelper(root);
        return ans.stream().mapToInt(Integer::intValue).toArray();
    }
}

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:

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:

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

最近公共父节点。 这题是要从下往上扫,扫到目标节点的路径要标识出来,在两条路径的首次交会,返回当前节点。 从下往上扫就是回溯,所以用后序遍历 注意条件。在后序遍历的当前节点处理中,若当前节点等于p,直接可以返回当前节点。同理,等于q时也返回。 之后,处理后序遍历返回的左右子节点。若左右子节点同时不空,意味着当前节点即答案。直接返回当前。 若左不空,返回左。 若右不空,返回右。 上述逻辑也适合于p或q即为答案的情况。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {

        if(root == null) {
            return null;
        }
        if(root.val == p.val) {
            return root;
        }

        TreeNode tleft = lowestCommonAncestor(root.left, p, q);
        TreeNode tright = lowestCommonAncestor(root.right, p, q);

        if(root.val == p.val) {
            return root;
        }
        else if(root.val == q.val) {
            return root;
        }
        else {
            if(tleft != null && tright != null) {
                return root;
            }
            else if (tleft == null) {
                return tright;
            }
            else {
                return tleft;
            }
        } 


    }
}