530. Minimum Absolute Difference in BST

xiaoxiao2021-02-27  186

Question

Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

Example:

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).

2 \ 4443 / 1329 \ 2917 \ 4406

The minimum absolute difference is 37, which is the difference between 4443 and 4406.

代码实现

1) we need compare nearby 2) every root to rightest of left subtree, every root to leftest of right subtree. this method beats 97% of submission.

public class Solution { public int GetMinimumDifference(TreeNode root) { //we need compare root to root.right, root to root.left, //every root to rightest of left subtree, every root to leftest of right subtree int min = getNearby(root); return Math.Min(min,getRootDiff(root)); } //we need compare root to root.right, root to root.left, private int getNearby(TreeNode root) { if (root.left == null && root.right == null) return Int32.MaxValue; int min = 0; if (root.left != null) { min = root.val - root.left.val; min = Math.Min(min, getNearby(root.left)); } if (root.right != null) { if (root.left != null) { min = Math.Min(min, root.right.val - root.val); min = Math.Min(min, getNearby(root.right)); } else { min = root.right.val - root.val; min = Math.Min(min, getNearby(root.right)); } } return min; } //every root to rightest of left subtree, every root to leftest of right subtree. private int getRootDiff(TreeNode root) { int min = Int32.MaxValue; if (root == null) return min; if (root.left == null && root.right == null) return min; var node = root; //root to rightest of left subtree if (root.left != null) { node = node.left; while (node.right != null) node = node.right; min = Math.Min(Math.Abs(root.val - node.val), min); } //root to leftest of right subtree if (root.right != null) { node = root.right; while (node.left != null) node = node.left; min = Math.Min(Math.Abs(node.val - root.val), min); } min = Math.Min(min, getRootDiff(root.left)); min = Math.Min(min, getRootDiff(root.right)); return min; } }

题库

leetcode算法题目解决方案每天更新在github库中,欢迎感兴趣的朋友加入进来,也欢迎star,或pull request。https://github.com/jackzhenguo/leetcode-csharp

转载请注明原文地址: https://www.6miu.com/read-13806.html

最新回复(0)