class Solution {
public int getMinimumDifference(TreeNode root) {
int leftMin = Integer.MAX_VALUE;
int rightMin = Integer.MAX_VALUE;
int minl = Integer.MAX_VALUE;
int minr = Integer.MAX_VALUE;
if(root.left != null){
TreeNode left = root.left;
while(left.right != null){
left = left.right;
}
minl = Math.abs(root.val - left.val);
leftMin = getMinimumDifference(root.left);
}
if(root.right != null){
TreeNode right = root.right;
while(right.left != null){
right = right.left;
}
minr = Math.abs(root.val - right.val);
rightMin = getMinimumDifference(root.right);
}
return Math.min(Math.min(minl,minr),Math.min(leftMin,rightMin));
}
}
思路:
当前节点记录4个最小值:
1.节点值与左子树中的最大值的差
2.节点值与右子树中的最小值的差
3.左子树中的最小差值
4.右子树中的最小差值
取这4个值的最小差值return
因为是二叉搜索树,中序遍历是升序数组,只要记录前后节点的差值,取最小就好
DFS版本
class Solution {
TreeNode pre;
int result = Integer.MAX_VALUE;
public int getMinimumDifference(TreeNode root) {
dfs(root);
return result;
}
public void dfs(TreeNode node){
if(node == null) return;
dfs(node.left);
if(pre != null){
result = Math.min(result,Math.abs(node.val - pre.val));
}
pre = node;
dfs(node.right);
}
}
迭代法
class Solution {
public int getMinimumDifference(TreeNode root) {
Deque<TreeNode> st = new LinkedList<>();
TreeNode pre = new TreeNode(-1);
TreeNode cur = root;
int result = Integer.MAX_VALUE;
while(!st.isEmpty() || cur != null){
if(cur != null){ //左
st.addLast(cur);
cur = cur.left;
}else{ //中
cur = st.pollLast();
if(pre.val != -1) result = Math.min(result,cur.val - pre.val);
pre = cur;
cur = cur.right; //右
}
}
return result;
}
}