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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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