783 二叉搜索树结点最小距离

第一种解法:两次遍历
因为题目中已经提示了“二叉搜索树”,所以我们用中序遍历就可以得到一个从小到大的数组。然后遍历数组找到最小的差值。
class Solution {
ArrayList<Integer> list = new ArrayList<>();
public int minDiffInBST(TreeNode root) {
inorderTraverse(root);
int res = Integer.MAX_VALUE;
for (int i = 0, len = list.size(); i < len - 1; ++i) {
int temp = Math.abs(list.get(i) - list.get(i + 1));
res = res < temp ? res : temp;
}
return res;
}
public void inorderTraverse(TreeNode node) {
if (node == null) {
return;
}
inorderTraverse(node.left);
list.add(node.val);
inorderTraverse(node.right);
}
}
一次遍历:用迭代的方式来遍历树
用迭代的方式来遍历,用一次遍历的方式来解决这个问题。
class Solution {
ArrayList<Integer> list = new ArrayList<>();
int min = Integer.MAX_VALUE;
public int minDiffInBST(TreeNode root) {
inorderTraversal(root);
return min;
}
public void inorderTraversal(TreeNode root) {
Integer preValue = null;
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
if (current != null) {
stack.push(current);
current = current.left;
} else {
current = stack.pop();
if (preValue != null) {
int temp = Math.abs(preValue - current.val);
min = min < temp ? min : temp;
}
preValue = current.val;
current = current.right;
}
}
}
}
本文介绍了一种解决二叉搜索树中结点最小距离问题的算法,通过中序遍历将二叉搜索树转化为有序数组,进而求得任意两相邻结点之间的最小差值。文章提供了两种解法,一种是两次遍历,另一种是一次遍历的方法。
305

被折叠的 条评论
为什么被折叠?



