Minimum Distance Between BST Nodes
找BST上两个node之间的最小值, 因为是bst所以已经是sorted了, 直接比较就可以
1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Solution { TreeNode prev = null; int res = Integer.MAX_VALUE; public int minDiffInBST(TreeNode root) { if (root == null) return res; int leftMin = minDiffInBST(root.left); res = Math.min(res, leftMin); if (prev != null) { res = Math.min(res, root.val - prev.val); } prev = root; int rightMin = minDiffInBST(root.right); res = Math.min(res, rightMin); return res; } } |