JAVA版本:
思路:本题是二叉排序树,所以我们进行中序遍历就能将二叉树按照递增的顺序来进行排序,然后我们只需要比较两个相邻的结点找到最小值即可。
解法1:
递归:思路与上题验证二叉搜索树有着相同的思想,使用pre结点来保存上一个结点,然后进行节点之间的比较。
class Solution {
TreeNode pre;//用来记录上一个结点
int result = Integer.MAX_VALUE; //我们要找到最新的绝对值的差,所以我们设置一个最大值
public int getMinimumDifference(TreeNode root) {
if(root==null)return 0;
traversal(root);
return result;
}
public void traversal(TreeNode root){
if(root==null)return;
//中序遍历
//左
traversal(root.left);
//中,中间的就是结果
//前一个节点不为空就进行比较
if(pre!=null){
result = Math.min(result,root.val-pre.val);
}
pre = root;
//右
traversal(root.right);
}
}
解法2:
迭代的思想去输出,将中序遍历的迭代法改善一下即可。
class Solution {
public int getMinimumDifference(TreeNode root) {
TreeNode pre = null; //声明一个之前的结点
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
int result = Integer.MAX_VALUE;
//结束条件是以读取了所有的结点,并且栈中无数据
while (cur != null || !stack.isEmpty()) {
//中序遍历
if(cur !=null) {
stack.push(cur);//访问的结点放入栈中
cur =cur.left;
}else{
cur = stack.pop();
if (pre != null) { // 中
result = Math.min(result, cur.val - pre.val);
}
pre = cur;
cur = cur.right; // 右
}
}
return result;
}
}
解法3: 将该二叉树使用中序遍历得到一个新的数组,再在数据中找到两个两个之间的最小绝对值的差。(该方法不再写出)