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; } }
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/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...
閱讀 718·2021-10-14 09:42
閱讀 1972·2021-09-22 15:04
閱讀 1577·2019-08-30 12:44
閱讀 2140·2019-08-29 13:29
閱讀 2734·2019-08-29 12:51
閱讀 548·2019-08-26 18:18
閱讀 702·2019-08-26 13:43
閱讀 2809·2019-08-26 13:38