开始之前先给自己打个鸡血吧:
A journey of a thousand miles begins with a single step. 千里之行始于足下。
题源:https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
题目详情:
给你一个二叉搜索树的根节点 root ,返回 树中任意两不同节点值之间的最小差值 。
差值是一个正数,其数值等于两值之差的绝对值。
思路
递归
代码
python
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 100000
if not root.left and not root.right:
return 100000
if not root.left and root.right:
return min(self.getRmin(root.right)-root.val,self.getMinimumDifference(root.right))
if root.left and not root.right:
return min(abs(self.getLmax(root.left)-root.val),self.getMinimumDifference(root.left))
return min(min(self.getRmin(root.right)-root.val,self.getMinimumDifference(root.right)),min(abs(self.getLmax(root.left)-root.val),self.getMinimumDifference(root.left)))
#找左子树的最大值
def getLmax(self,root):
if root.right:
return self.getLmax(root.right)
return root.val
#找右子树的最小值
def getRmin(self,root):
if root.left:
return self.getRmin(root.left)
return root.val
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int getMinimumDifference(TreeNode root) {
if(root==null) return 100000;
else if((root.left==null)&&(root.right==null)) return 100000;
else if((root.left==null)&&(root.right!=null)){
return Math.min(getRmin(root.right)-root.val,getMinimumDifference(root.right));
}
else if((root.left!=null)&&(root.right==null)){
return Math.min(root.val-getLmax(root.left),getMinimumDifference(root.left));
}
else{
return Math.min(Math.min(getRmin(root.right)-root.val,getMinimumDifference(root.right)),Math.min(root.val-getLmax(root.left),getMinimumDifference(root.left)));
}
}
public int getLmax(TreeNode root){
if(root.right!=null){
return getLmax(root.right);
}
return root.val;
}
public int getRmin(TreeNode root){
if(root.left!=null){
return getRmin(root.left);
}
return root.val;
}
}