原题
https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
思路
利用中序遍历递增的性质
- (1)中序遍历得到一个递增的集合,遍历集合得到
min
- (2)遍历过程中记录
pre
,直接得到min
题解
/**
* 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 {
public int minDiffInBST(TreeNode root) {
// 中序遍历计数
List<Integer> list = new ArrayList<>();
midOrder(root, list);
int len = list.size();
int res = Integer.MAX_VALUE;
for (int i = 1; i < len; i++) {
res = Math.min(res, list.get(i) - list.get(i-1));
}
return res;
}
private static void midOrder(TreeNode node, List<Integer> list){
if (node.left != null) {
midOrder(node.left, list);
}
list.add(node.val);
if (node.right != null) {
midOrder(node.right, list);
}
}
}
/**
* 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 {
int pre;
int min;
public int minDiffInBST(TreeNode root) {
min = Integer.MAX_VALUE;
pre = -1;
midOrder2(root);
return min;
}
private void midOrder2(TreeNode node){
if (node.left != null) {
midOrder2(node.left);
}
if (pre == -1) {
pre = node.val;
} else {
min = Math.min(min, node.val - pre);
pre = node.val;
}
if (node.right != null) {
midOrder2(node.right);
}
}
}