给定一棵二叉搜索树,它的根结点为root。求这棵树中不同结点的最小差值。 【Map02-BST】public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x;
}
}
比如:
4
/
2 6
/
1 3
这棵树中,最小差值为1. (2结点和1结点,3结点和2结点)
public static void main(String[] args) {
List list1 = Arrays.asList(10,7,1,9,12);
List list2 = Arrays.asList(1,7,9,10,12);
BinarySearchTree tree = BinarySearchTree.buildTree(list1, list2);
System.out.println(getMinDiff(tree));
}private static int getMinDiff(BinarySearchTree tree) {
List list = tree.inOrder();
if (list.size() < 2) throw new IllegalStateException("结点小于2,无法求差值");
int min = list.get(1) - list.get(0);
for (int i = 2;
i < list.size();
i++) {
min = Math.min(list.get(i) - list.get(i - 1), min);
}
return min;
}public List inOrder() {
List list = new ArrayList<>();
inOrder(root, list);
return list;
}private void inOrder(TreeNode node, List list) {
if (node == null) return;
// 遍历左子树
inOrder(node.left, list);
// 遍历根节点
list.add(node.value);
// 遍历右子树
inOrder(node.right, list);
}