/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<Integer> list = new ArrayList<>();
public int minDiffInBST(TreeNode root) {
int ans = Integer.MAX_VALUE;
inOrder(root);
for (int i = 1; i < list.size(); i++) {
ans = Math.min(ans, list.get(i) - list.get(i - 1));
}
return ans;
}
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
inOrder(root.left);
}
int val = root.val;
list.add(val);
if (root.right != null) {
inOrder(root.right);
}
}
}
评论