Minimum Distance Between BST Nodes
Given the root of a Binary Search Tree(BST), return the minimum difference between the values of any two different nodes in the tree.
今天的题目是求二叉搜索树的节点之间的最小距离,即求树中任意两个节点差值的最小值。而我们知道,二叉搜索树的特点是,左子树一定小于根节点,右子树一定大于根节点,而且二叉搜索树的中序遍历结果正好是按照从小到大的顺序排列的,所以只需要将二叉搜索树中序遍历,再对其结果列表每个相邻的元素,求它们差的最小值即可。
这是一道简单难度的题目,直接上代码:
TreeNode.java
/**
* @author: LittleWang
* @date: 2021/4/13
* @description:
*/
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;
}
}
Solution.java
import java.util.ArrayList;
import java.util.List;
/**
* @author: LittleWang
* @date: 2021/4/13
* @description:
*/
public class Solution {
public int minDiffInBST(TreeNode root) {
List<Integer> valueList = new ArrayList<>();
inorder(valueList, root);
int result = valueList.get(valueList.size()-1); //最终结果一定小于二叉搜索树中的最大值,所以给result取初值为最大值
for (int i = 0; i < valueList.size()-1; i++) {
if((valueList.get(i+1)-valueList.get(i)) < result) {
result = valueList.get(i+1)-valueList.get(i);
}
}
return result;
}
public void inorder(List<Integer> list, TreeNode treeNode) { //中序遍历二叉搜索树
if(treeNode == null)
return;
if(treeNode.left != null)
inorder(list, treeNode.left);
list.add(treeNode.val);
if(treeNode.right != null)
inorder(list, treeNode.right);
}
}
提交结果: