Saturday, February 10, 2018

LeetCode 783. Minimum Distance Between BST Nodes - Weekly Contest 71

https://leetcode.com/contest/weekly-contest-71/problems/minimum-distance-between-bst-nodes/
Given a Binary Search Tree (BST) with the root node root, return the minimum difference between the values of any two different nodes in the tree.

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int minDiffInBST(TreeNode root) {
// filter abnormal cases
if (root == null) {
return 0;
}
nodes = new LinkedList<>();
helper(root);
// return the final result
int answer = Integer.MAX_VALUE;
int slow = nodes.getFirst();
for (int i = 1; i < nodes.size(); i++) {
int fast = nodes.get(i);
answer = Math.min(answer, Math.abs(fast - slow));
slow = fast;
}
return answer;
}
LinkedList<Integer> nodes;
public void helper(TreeNode root) {
if (root == null) {
return;
}
helper(root.left);
nodes.add(root.val);
helper(root.right);
}
}

No comments:

Post a Comment