Problem
Minimum Absolute Difference in BST
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Input:
1 3 / 2
Output:
1
Explanation:
The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
public class Solution { /** * @param root: the root * @return: the minimum absolute difference between values of any two nodes */ private final int diff = Integer.MAX_VALUE; public int getMinimumDifference(TreeNode root) { // take root for example, the min diff should be the diff of // 1. `root` and `root.left"s rightmost child` // 2. `root` and `root.right"s leftmost child` if (root == null) return diff; int res = Integer.MAX_VALUE, leftmost = -1, rightmost = -1; if (root.left != null) { rightmost = getRightMost(root.left); } if (root.right != null) { leftmost = getLeftMost(root.right); } if (leftmost != -1) { res = Math.min(res, Math.abs(root.val - leftmost)); } if (rightmost != -1) { res = Math.min(res, Math.abs(root.val - rightmost)); } res = Math.min(res, getMinimumDifference(root.left)); res = Math.min(res, getMinimumDifference(root.right)); return res; } public int getLeftMost(TreeNode node) { while (node.left != null) node = node.left; return node.val; } public int getRightMost(TreeNode node) { while (node.right != null) node = node.right; return node.val; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/71380.html
Problem Given an integer array, adjust each integers so that the difference of every adjacent integers are not greater than a given number target. If the array before adjustment is A, the array after ...
Problem Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute dif...
Problem Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at ...
摘要:递归左右子树,若左右子树都有解,那么返回根节点若仅左子树有解,返回左子树若仅右子树有解,返回右子树若都无解,返回。对于而言,更为简单公共祖先一定是大于等于其中一个结点,小于等于另一个结点。 Problem Given the root and two nodes in a Binary Tree. Find the lowest common ancestor(LCA) of the ...
Problem Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both nu...
阅读 711·2021-10-14 09:42
阅读 1966·2021-09-22 15:04
阅读 1569·2019-08-30 12:44
阅读 2133·2019-08-29 13:29
阅读 2728·2019-08-29 12:51
阅读 541·2019-08-26 18:18
阅读 697·2019-08-26 13:43
阅读 2803·2019-08-26 13:38