给你一个二叉搜索树的根节点 root
,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
方法一:中序遍历
public int getMinimumDifference(TreeNode root){
Deque<TreeNode> stack = new LinkedList<>();
List<Integer> list = new ArrayList<>();
while(!stack.isEmpty() || root != null){
while(root != null){
stack.push(root);
root = root.left;
}
// 中序遍历中树节点要一直用一个节点,不能在外层while循环中再定义树节点
// TreeNode node = stack.pop();
// list.add(node.val);
// node = node.right;
root = stack.pop();
list.add(root.val);
root = root.right;
}
int min = Integer.MAX_VALUE;
for(int i = 0; i < list.size() - 1; i++){
int temp = list.get(i + 1) - list.get(i);
min = min > temp ? temp : min;
}
return min;
}